This is my exact code for editing the record in my text file.
My codes are run successfully, but the records within text file doesn't update once I clicked btnModify. What's wrong with my codes?
P.s: These codes are used for my awt program.
btnModify.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ArrayList<String> tempData = new ArrayList<>();
String requestedID = txtID.getText().trim().toLowerCase();
String requestedName = txtName.getText().trim();
String requestedGender = txtGender.getText().trim();
String requestedContactNumber = txtContactNumber.getText().trim();
System.out.println("123");
try {
FileReader fr = new FileReader("test.txt")){
Scanner reader = new Scanner(fr);
System.out.println("123456");
while (reader.hasNext()){
String line = reader.nextLine();
String lineLtrim = line.toLowerCase().replaceAll("^\\{", "");
String lineRtrim = lineLtrim.replaceAll("\\}$", "");
String[] data = lineRtrim.split(",");
System.out.println("5566");
if(data[0].equals(requestedID)){
System.out.println("9999");
data[1] = data[1].replace(data[1], requestedName);
data[2] = data[2].replace(data[2], requestedGender);
data[3] = data[3].replace(data[3], requestedContactNumber);
tempData.add(data[0] + "," + data[1] + "," + data[2] + "," + data[3] );
outStream.write("{" + txtID.getText().replace(data[0], requestedID));
outStream.write("," + txtName.getText().replace(data[1], requestedName));
outStream.write("," + txtGender.getText().replace(data[2], requestedGender));
outStream.write("," + txtContactNumber.getText().replace(data[3], requestedContactNumber) + "}");
outStream.write("\r\n");
outStream.close();
System.out.println("632");
System.out.println(tempData);
JOptionPane.showMessageDialog(null, "Modify Successful!");
}
else {
tempData.add(data[0] + ":" + data[1] + ":" + data[2] + ":" + data[3]);
System.out.println("142");
System.out.println(tempData);
}
}
fr.close();
}
catch (Exception ex){
}
}
});
This is my text file format.
{001,Jack,male,0123456789}
{002,Mark,male,0198765432}
Related
When I open the view window, I enter the value of facultyCode and if I enter an existing value, then everything is fine, and if I enter a non-existent value, then the window freezes and nothing happens
CLIENT
#FXML
void initialize() {
showButton.setOnAction(actionEvent -> {
String input = null;
try {
socket = new Socket("127.0.0.1",3024);
outputStream = new DataOutputStream(socket.getOutputStream());
inputStream = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
String facultyCode = facultyCodeArea.getText();
String output = "SELECT * FROM Faculty WHERE facultyCode = " + facultyCode + ";";
try {
outputStream.writeUTF(output);
outputStream.flush();
input = inputStream.readUTF(); //if the input is incorrect, input is not assigned to
//anything
} catch (IOException e) {
e.printStackTrace();
}
String[] dataServer = input.split(" ");
String name = dataServer[0];
nameArea.setText(name);
String code = dataServer[1];
facultyCodeArea.setText(code);
String number = dataServer[2];
numberSubjectsArea.setText(number);
String main = dataServer[3];
mainSubjectArea.setText(main);
String dean = dataServer[4];
deanArea.setText(dean);
String language = dataServer[5];
languageStudyArea.setText(language);
});
}
SERVER
else if (isSelectQuery(input)) {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(input);
while (resultSet.next()) {
String name = resultSet.getString("name");
int codeFaculty = resultSet.getInt("facultyCode");
int numberSubject = resultSet.getInt("numberSubjects");
String mainSubject = resultSet.getString("mainSubject");
String dean = resultSet.getString("dean");
String languageStudy = resultSet.getString("languageStudy");
String output = name + " " +
codeFaculty + " " +
numberSubject + " " +
mainSubject + " " +
dean + " " +
languageStudy;
outputStream.writeUTF(output);
outputStream.flush();
}
}
I've tried closing the window if an exception occurs, I've also tried closing the window if input = null, but didn't help
SERVER
String output = "error";
else if (isSelectQuery(input)) {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(input);
while (resultSet.next()) {
String name = resultSet.getString("name");
int codeFaculty = resultSet.getInt("facultyCode");
int numberSubject = resultSet.getInt("numberSubjects");
String mainSubject = resultSet.getString("mainSubject");
String dean = resultSet.getString("dean");
String languageStudy = resultSet.getString("languageStudy");
output = name + " " +
codeFaculty + " " +
numberSubject + " " +
mainSubject + " " +
dean + " " +
languageStudy;
}
outputStream.writeUTF(output);
outputStream.flush();
}
CLIENT
#FXML
void initialize() {
showButton.setOnAction(actionEvent -> {
String input = null;
try {
socket = new Socket("127.0.0.1",3024);
outputStream = new DataOutputStream(socket.getOutputStream());
inputStream = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
String facultyCode = facultyCodeArea.getText();
String output = "SELECT * FROM Faculty WHERE facultyCode = " + facultyCode + ";";
try {
outputStream.writeUTF(output);
outputStream.flush();
input = inputStream.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
String[] dataServer = input.split(" ");
if(!dataServer[0].equals("error")) {
String name = dataServer[0];
nameArea.setText(name);
String code = dataServer[1];
facultyCodeArea.setText(code);
String number = dataServer[2];
numberSubjectsArea.setText(number);
String main = dataServer[3];
mainSubjectArea.setText(main);
String dean = dataServer[4];
deanArea.setText(dean);
String language = dataServer[5];
languageStudyArea.setText(language);
}
else {
errorArea.setText("Not exist");
}
});
}
So I first assign output = error and if the request does not return anything, then I send it to the client, if on request something came, I assign values and send it to the client. Next, I process the data on the client
I wrote a big chunk of codes that downloads CSV file from url, then i bulk inserted into sql database, then call data from SQL server and display on Java console. Finally select the column I want to keep and export as a new CSV file.
but all of those codes are in the same class right now. How can I separate them into different class like I want a class for just download file and another class just do the Bulk insert and another class to just do the Select Query.
Thanks for helping me out
below is my code in one class now
public class ProjectTest extends CreateTable {
public static void main(String[] args) throws MalformedURLException {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
URL url = new URL(
"https://quality.data.gov.tw/dq_download_csv.php?nid=43983&md5_url=9d38afbca8243a24b5b89d03a8070aff");
try (InputStream inputStream = url.openStream();
FileOutputStream fos = new FileOutputStream(
"C:\\Users\\ALICE\\Desktop\\Java\\Dropbox\\Java\\virus.csv");
Connection connection = DriverManager
.getConnection("jdbc:sqlserver://localhost:1433;databaseName=JDBCDB", "andy3", "andy"); // andy3
// //
// ,andy
Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
FileOutputStream fos2 = new FileOutputStream(
"C:\\Users\\ALICE\\Desktop\\Java\\Dropbox\\Java\\NEWvirus.csv");
OutputStreamWriter osw = new OutputStreamWriter(fos2, "MS950");
BufferedWriter bw = new BufferedWriter(osw);
) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fos.close();
stmt.executeUpdate("DROP TABLE Virus");
boolean rs = stmt.execute(CreateTable);
System.out.println("Database Created");
PreparedStatement pstmt = connection.prepareStatement(InsertData);
int executeUpdate = pstmt.executeUpdate();
if (executeUpdate > 0) {
System.out.println("Data Inserted");
} else {
System.out.println("Insert ERROR");
}
ResultSet rs4 = stmt.executeQuery("SELECT Count(*) FROM Virus");
int numberOfData = rs4.getInt(1);
System.out.println(numberOfData);
ResultSet rs3 = stmt.executeQuery(selectQuery);
ResultSetMetaData metaData = rs3.getMetaData();
DatabaseMetaData DmetaData = connection.getMetaData();
String[] types = { "TABLE" };
ResultSet rs5 = DmetaData.getTables(null, null, "Virus", types);
List<String> ColNameList = new ArrayList<String>();
while (rs5.next()) {
String tableName = rs5.getString("TABLE_NAME");
ResultSet columnRs = DmetaData.getColumns(null, null, tableName, null);
while (columnRs.next()) {
String columnName = columnRs.getString("COLUMN_NAME");
ColNameList.add(columnName);
}
System.out.print("|" + ColNameList.get(0) + " |");
System.out.print(ColNameList.get(1) + " |");
System.out.print(ColNameList.get(2) + "|");
System.out.print(ColNameList.get(3) + "|");
System.out.print(ColNameList.get(4) + " |");
System.out.print(ColNameList.get(5) + " |");
System.out.print(ColNameList.get(6) + " |");
System.out.print(ColNameList.get(7) + " |");
System.out.print(ColNameList.get(8) + "|");
System.out.print(ColNameList.get(9) + " |");
System.out.print(ColNameList.get(10) + " |");
System.out.print(ColNameList.get(11) + "|");
System.out.print(ColNameList.get(12) + " |");
System.out.print(ColNameList.get(13) + " |");
System.out.print(ColNameList.get(14) + " |");
System.out.print(ColNameList.get(15) + "");
}
System.out.println();
while (rs3.next()) {
coList1.add(rs3.getString(1));
coList2.add(rs3.getString(2));
coList3.add(rs3.getString(3));
coList4.add(rs3.getString(4));
coList5.add(rs3.getString(5));
coList6.add(rs3.getString(6));
coList7.add(rs3.getString(7));
coList8.add(rs3.getString(8));
coList9.add(rs3.getString(9));
coList10.add(rs3.getString(10));
coList11.add(rs3.getString(11));
coList12.add(rs3.getString(12));
coList13.add(rs3.getString(13));
coList14.add(rs3.getString(14));
coList15.add(rs3.getString(15));
coList16.add(rs3.getString(16));
coList17.add(rs3.getString(17));
}
for (int p = 0; p < 20; p++) { // coList9.size(
System.out.print("|" + coList1.get(p) + "|");
String str2 = coList2.get(p);
if (str2.length() < 3) {
String blank = " ";
String repeated = new String(new char[(3 - str2.length())]).replace("\0", blank);
System.out.print(repeated + coList2.get(p) + "|");
} else {
System.out.print(coList2.get(p) + "|");
}
System.out.print(" " + coList3.get(p) + "|");
System.out.print(coList4.get(p) + "|");
System.out.print(coList5.get(p) + "|");
System.out.print(coList6.get(p) + "|");
System.out.print(coList7.get(p) + "|");
System.out.print(coList8.get(p) + "|");
String str = coList9.get(p);
if (str.length() < 5) {
String blank = " ";
String repeated = new String(new char[(5 - str.length())]).replace("\0", blank);
System.out.print(repeated + coList9.get(p) + "|");
} else {
System.out.print(coList9.get(p) + "|");
}
System.out.print(coList10.get(p) + "|");
System.out.print(coList11.get(p) + "|");
String str12 = coList12.get(p);
if (str12.length() < 5) {
String blank = " ";
String repeated = new String(new char[(6 - str12.length())]).replace("\0", blank);
System.out.print(repeated + coList12.get(p) + "|");
} else {
System.out.print(coList12.get(p) + "|");
}
String str13 = coList13.get(p);
if (str13.length() < 5) {
String blank = " ";
String repeated = new String(new char[(4 - str13.length())]).replace("\0", blank);
System.out.print(repeated + coList13.get(p) + "|");
} else {
System.out.print(coList12.get(p) + "|");
}
System.out.print(coList14.get(p) + "|");
System.out.print(coList15.get(p) + "|");
System.out.print(coList16.get(p) + "|");
System.out.print(coList17.get(p) + "|");
System.out.println();
}
rs3.beforeFirst();
StringBuilder builder = new StringBuilder();
builder.append("CaseID").append(",").append("Age").append(",").append("Gender").append(",").append("City")
.append(",").append("SampleDate").append(",").append("VirusType").append(",")
.append("SubType").append(",").append("Locus").append(",").append("Primer").append(",").append("GeneDirection")
.append(",").append("TypingMethod").append(",").append("DNASeq").append(",").append("AminoAcidSeq");
System.out.println(rs3.next());
while (rs3.next()) {
builder.append(System.lineSeparator());
builder.append(rs3.getString(1)).append(",").append(rs3.getString(2)).append(",")
.append(rs3.getString(3)).append(",").append(rs3.getString(5)).append(",")
.append(rs3.getString(7)).append(",").append(rs3.getString(10)).append(",")
.append(rs3.getString(11)).append(",").append(rs3.getString(12)).append(",")
.append(rs3.getString(13)).append(",").append(rs3.getString(14)).append(",")
.append(rs3.getString(15)).append(",").append(rs3.getString(16)).append(",").append(rs3.getString(17)).append(",");
}
bw.write(builder.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
Start refactoring your code in small steps and then iteratively improve your design if needed.
As you have mentioned the algorithmic approach, leveraging that this should be your starting step.
CSV file from url,
then i bulk inserted into sql database,
then call data from SQL server and
display on Java console.
Finally select the column I want to keep
and export as a new CSV file.
Small helper functions for each of these steps.
Read more about SOLID design principles if that helps in improving your solution.
try {
String hour = (String) comboBox.getSelectedItem();
String filename = fileName.getText();
String date = ((JTextField)dateChooser.getDateEditor().getUiComponent()).getText();
String text = txtKeyword.getText();
String newline = "\n";
String directory = Directory.getText();
File path = new File(directory);
File[] faFiles = path.listFiles();
for(File file: faFiles){
**if(file.getName().contains(filename + "-" + date + "[" + hour + "]") == true == true || file.getName().contains(filename + "-" + date) || file.getName().contains(filename)){**
String line = null;
Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
if(line.contains(text)){
jTextArea1.append(line + newline);
btnClear.setEnabled(true);
btnExport.setEnabled(true);
}
}
br.close();
}
}
}
catch(Exception e){
}
Here is my question. I'm trying to use input and loop method to search for a file. The above code works but my problem is lets say I try to find 2 different text files
1. billing-20140527[09].txt has
a)XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)XGMS,2034-05-27 30:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
2. billing-20140527[10].txt has
a)XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)HELO
**I try to find the number 1 in both text files, if lets say I input the text file name is
billing, I can find the number 1 in both text file and output them:**
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b) XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
**However, if I specify the text file name: billing-20140527[09].txt and find the number 1 inside the text file, it will only output:
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.**
Can anyone help me with this? Guide or help?
I would work with the BufferedReader. Because it reads a whole line. And then you can split the line by a delimiter (lets say a space " " ). In your case I would write a split-method which receives a String and search for the regex you want.
private void doSearch(File f2) throws IOException,
fileHandler.FileException {
File[] children = f2.listFiles();
if (children != null && searching)
for (int i = 0; i < children.length; i++) {
if (g.isReady()) {
g.setReady(false);
if (!searching) {
g.setReady(true);
break;
} else if (isDirectory(children[i])) {
g.getActualDirectoryInhalt().setText(children[i].getPath()
.substring(g.root.getText().length()));
counterDirectories++;
doSearch(children[i]);
} else if (advancedSearch && !filterSpecified(children[i])) {
raiseCounterForDirectorySize(children[i]);
continue;
} else if (checkFile(children[i])) {
counterFiles++;
searchThroughFile(children[i], this.regex);
raiseCounterForDirectorySize(children[i]);
} else {
g.getTextAreaUnreachable().setText(
g.getTextAreaUnreachable().getText() + f2
+ "\n");
raiseCounterForDirectorySize(children[i]);
}
} else {
doSearch(children[i]);
}
g.setReady(true);
}
}
And here's the other method:
public static void searchThroughFile(File f2, String regex) throws IOException,
fileHandler.FileException {
try {
InputStream is = new BufferedInputStream(new FileInputStream(f2));
String mimeType = URLConnection.guessContentTypeFromStream(is);
ArrayList<String> linesFromFile = fileHandler.FileReaderer
.readFileIntoStringArrayList(f2);
String line = null;
if (f2.getAbsolutePath().contains(regex)) {
g.getTextAreaAdvanced()
.setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + "\n");
}
if (linesFromFile.size() != 0) {
for (int i = 0; i < linesFromFile.size(); i++) {
line = linesFromFile.get(i);
Pattern MY_Pattern = Pattern.compile(regex);
Matcher m = MY_Pattern.matcher(line);
if (!searching) {
break;
}
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
while (m.find() && searching) {
counterFoundPattern++;
g.getFoundFilesInhalt().setText(counterFoundPattern + "");
if (mimeType != null) {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + mimeType + " " + i+1 + "\n");
} else {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + i+1 + "\n");
}
}
g.setReady(true);
}
}
} catch (IOException e) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTabpane().setForegroundAt(2, Color.RED);
g.getTextAreaException().setText(
g.getTextAreaException().getText() + e + "\n");
g.setReady(true);
} catch (OutOfMemoryError oute) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTextAreaException().setText(
g.getTextAreaException().getText() + "\n"
+ "Fatal Error encured! The File will be skipped!"
+ "\n" + f2.getAbsolutePath());
g.getTabpane().setSelectedIndex(2);
g.setReady(true);
return;
}
}
How can I split a flat string based on 0102**? string tokenizer is working for only **. Is there any way to split based on 0102**? Please suggest
Here is my complete method
private String handleCibil(InterfaceRequestVO ifmReqDto, String szExtIntType) throws MalformedURLException, org.apache.axis.AxisFault, RemoteException {
/* Declaration and initiliazation */
ConfVO confvo = ifmReqDto.getExtConfVo();
String szResponse = null;
String cibilResponse = null;
String errorResponse = null;
String endpointURL = null;
long timeOut = confvo.getBurMgr().getBurInfo(szExtIntType).getTimeOut();
endpointURL = formWebServiceURL(confvo, szExtIntType);
URL url = new URL(endpointURL);
log.debug("Input xml for cibil "+ifmReqDto.getIfmReqXML());
BasicHttpStub stub= new BasicHttpStub(url,new org.apache.axis.client.Service());
szResponse = stub.executeXMLString(ifmReqDto.getIfmReqXML());
//szResponse=szResponse.replaceAll("&", "&");
log.debug("szResponse "+szResponse);
/* Validate if the obtained response is as expected by IFM */
try {
extDao = new ExtInterfaceXMLTransDAO(ifmReqDto.getSemCallNo(), ifmReqDto.getIdService());
extDao.updateRqstRespXML10g(ifmReqDto.getInterfaceReqNum(), szResponse, GGIConstants.IFM_RESPONSE);
//log.debug("CIBIL_RESPONSE_XPATH " + GGIConstants.CIBIL_RESPONSE_XPATH);
Document xmlDocument = DocumentHelper.parseText(szResponse);
String xPath = GGIConstants.RESPONSE_XPATH;
List<Node> nodes = xmlDocument.selectNodes(xPath);
for (Node node : nodes) {
String keyValue = node.valueOf(GGIConstants.RESPONSE_XPATH_KEY);
// log.debug("keyValue : " + keyValue);
if (keyValue.equalsIgnoreCase(GGIConstants.RESPONSE_XPATH_KEY_VALUE)) {
// log.debug("node value : " + node.getText());
cibilResponse = node.getText();
}
}
log.debug("cibilResponse " + cibilResponse);
String errorResponseXPATH = GGIConstants.CIBIL_ERROR_RESPONSE_XPATH;
List<Node> errorResponseNode = xmlDocument.selectNodes(errorResponseXPATH);
for (Node node : errorResponseNode) {
errorResponse = node.getText();
}
log.debug("errorResponse " + errorResponse);
if(cibilResponse!=null && cibilResponse.length()>0)
{
StringTokenizer cibilResponseResults = new StringTokenizer(cibilResponse,"**");
String tempResponse="";
ArrayList probableMatchList = new ArrayList();
while (cibilResponseResults.hasMoreElements()) {
tempResponse = (String) cibilResponseResults.nextElement();
if(tempResponse.length()>=80)
{
String memberRefNo = tempResponse.substring(69, 80).replaceAll(" ", "");
log.debug("memberRefNo " + memberRefNo);
if (memberRefNo.length() > 0) {
if (Integer.parseInt(memberRefNo) > 0) {
cibilResponse = tempResponse;
cibilResponse = cibilResponse+"**";
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
cibilResponse = tempResponse+"**";
}
}
log.debug("After finding the Member reference number cibilResponse " + cibilResponse);
log.debug("After finding the Probable reference list " + probableMatchList);
// TKN 008
cibilResponse=StringEscapeUtils.unescapeXml(cibilResponse).replaceAll("[^\\x20-\\x7e]","");
ifmReqDto.setIfmTransformedResult(cibilResponse);
ifmReqDto.setProbableMatchList(probableMatchList);
}
if (errorResponse!=null && errorResponse.length()>0) {
throw new GenericInterfaceException(errorResponse
+ " for the seq_request " + ifmReqDto.getSeqRequest() + " Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.CIBIL_ERROR_CODE);
}
else if (cibilResponse==null || StringUtils.isEmpty(cibilResponse) ) {
throw new GenericInterfaceException("Cibil TUEF response is empty >> cibil Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.INTERFACE_ERROR_RESPONSE);
}
/* Setting Instinct response to ifmReqDto object */
} catch (SQLException e) {
log.error("SQLException while connecting to DataBase. Exception message is ", e);
throw new GenericInterfaceException("SQLException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.DB_OPERATION_ERROR);
} catch (GenericInterfaceException exp) {
log.error("Exception occured while valid:", exp);
throw exp;
} catch (Exception exp) {
log.error("Exception occured while valid:", exp);
throw new GenericInterfaceException("GeneralException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.UNKNOWN_ERROR);
}
return szResponse;
}
I recommend checking out the Java documentation, it provides a really good reference to start with. The .split method uses a regex to split up a string based on a delimiter.
String[] tokens = myString.split("0102\\*\\*");
For now I suspect that you forgot to escape * in split regex.
Try maybe
String[] resutl = yourString.split("0102\\*\\*");
In case you want * to represent any character then use . instead of *
String[] resutl = yourString.split("0102..");
In case you want * to represent any digit use \\d instead
String[] resutl = yourString.split("0102\\d\\d");
String string = "blabla0102**dada";
String[] parts = string.split("0102\\*\\*");
String part1 = parts[0]; // blabla
String part2 = parts[1]; // dada
Here we have a String: "blabla0102**dada", we call it string. Every String object has a method split(), using this we can split a string on anything we desire.
Do you mean literally split by "0102**"? Couldn't you use regex for that?
String[] tokens = "My text 0102** hello!".split("0102\\*\\*");
System.out.println(tokens[0]);
System.out.println(tokens[1]);
try {
final List<String> ar = new ArrayList<String>();
final PRIvariable pri = new PRIvariable();
final BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream("C:/cdr2.csv")));
while (reader.ready()) {
final String line = reader.readLine();
final String[] values = line.split(",");
pri.dateText = values[2] + " " + values[4];
pri.count = pri.count + 1;
pri.sum = pri.sum + Integer.parseInt(values[7]);
System.out.println(pri.dateText + " " + pri.sum + " " + pri.count);
ar.add(pri);
}
final String[] columnNames = { "Date", "TOTAL", "COUNTS" };
final String[][] cells = new String[ar.size()][3];
for (int i = 0; i < ar.size(); i++) {
cells[i][0] = ((PRIvariable) ar.get(i)).dateText;
cells[i][1] = "" + ((PRIvariable) ar.get(i)).sum;
cells[i][2] = "" + ((PRIvariable) ar.get(i)).count;
}
table = new JTable(cells, columnNames);
table.setSize(400, 400);
table.setVisible(true);
final JScrollPane js = new JScrollPane();
js.setViewportView(table);
js.setSize(400, 400);
js.setVisible(true);
add(js, java.awt.BorderLayout.CENTER);
} catch (final Exception e) {
System.out.println(e);
}
This is my code. Here i want to Read text file and put that data to Jtable. But in this code it shows every row of the Jtable filled with same data that contain in arraylist(ar) last row. ( i think there is problem in my arraylist). How can i solve this......
The problem is with the variable pri. It has to be created inside the while loop.
Like this
String line = null;
while ((line = reader.readLine()) != null) {
PRIvariable pri = new PRIvariable();
String[] values = line.split(",");
pri.dateText = values[2] + " " + values[4];
pri.count = pri.count + 1;
pri.sum = pri.sum + Integer.parseInt(values[7]);
System.out.println(pri.dateText + " " + pri.sum + " " + pri.count);
ar.add(pri);
}
In your code your want to create a separate instance of PRIvariable for every line in the file, but you are creating only once instance of PRIvariable at the beginning then you are always using that instance by overriding the previous value.