I have to read a txt file using file-dialog. It works for me but I have an if statement which should ignore ("/"), blank lines and ("["). The if-statement is not working, output is just the original data in txt file, how can I fix it. Below is the full method.
I'm expecting the data of txt file to be without "/" and "["
public void readToolData() { Frame myFrame = new Frame(); FileDialog fileName = new FileDialog(myFrame, "Open", FileDialog.LOAD); fileName.setDirectory("/"); fileName.setVisible(true);
if (fileName != null) {
String filePath = fileName.getDirectory() + fileName.getFile();
System.out.println("selected file:" + fileName);
File fileData = new File(filePath);
String typeOfData = "";
try {
// reading the file line by line scanner
Scanner read = new Scanner(fileData);
while (read.hasNextLine()) {
String lineOfText = read.nextLine().trim();
System.out.println(lineOfText);
// checking non empty or non comment | added ! to the or condition
if (!lineOfText.startsWith("/") && !lineOfText.startsWith("[") || lineOfText.isEmpty())
{
typeOfData = lineOfText;
Scanner lineReader = new Scanner(lineOfText).useDelimiter(",");
Tool t = new Tool();
this.storeTool(t);
} } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } } else { System.out.println("Error! No file selected!"); } }
Assuming the file in question looks something like this:
// this is a comment, any lines that start with //
// (and blank lines) should be ignored
[ElectricTool data]
// data is toolName, toolCode, timesBorrowed, onLoan, cost, weight, rechargeable, power
Makita BHP452RFWX,RD2001,12 , false,14995,1800,true,18V
Flex Impact Screwdriver FIS439,RD2834,14,true,13499,1200 ,true,10.8V
DeWalt D23650-GB Circular Saw, RD6582,54,true,14997,5400,false,1350W
Milwaukee DD2-160XE Diamond Core Drill,RD4734,50,false,38894,9000,false,1500W
Bosch GSR10.8-Li Drill Driver,RD3021,25, true,9995,820, true,10.8V
A regular expression or two would work well (I made a couple of other minor changes too):
public void readToolData() {
Frame myFrame = new Frame();
FileDialog fileName = new FileDialog(myFrame, "Select the file to load", FileDialog.LOAD);
fileName.setDirectory("/");
fileName.setVisible(true);
if (fileName.getDirectory() != null && fileName.getFile() != null) {
String filePath = fileName.getDirectory() + fileName.getFile();
System.out.printf("Selected file: %1$s\n", fileName);
File fileData = new File(filePath);
String typeOfData = "";
try {
// pattern for lines to be skipped
Pattern ptrnSkip = Pattern.compile("(?:^//|\\[)+?.*$");
// pattern for line delimiter - account for potential leading / trailing spaces
Pattern ptrnDlim = Pattern.compile(" *, *");
// read the file line by line
try (Scanner scnrFile = new Scanner(fileData)) {
while (scnrFile.hasNextLine()) {
String lineOfText = scnrFile.nextLine().trim();
// skip empty lines and comments
if (!lineOfText.isEmpty() && !ptrnSkip.matcher(lineOfText).matches()) {
System.out.printf("Line read: \"%1$s\"\n", lineOfText);
typeOfData = lineOfText;
try (Scanner scnrLine = new Scanner(lineOfText).useDelimiter(ptrnDlim)) {
String strDesc = scnrLine.next();
String strCode = scnrLine.next();
int iBorrowedCount = scnrLine.nextInt();
boolean bIsOnLoan = scnrLine.nextBoolean();
int iCost = scnrLine.nextInt();
int iWeight = scnrLine.nextInt();
boolean bIsRechargeable = scnrLine.nextBoolean();
String strPowerSrc = scnrLine.next();
System.out.printf(" Description: %1$s\n", strDesc);
System.out.printf(" Code: %1$s\n", strCode);
System.out.printf(" Borrowed count: %1$d\n", iBorrowedCount);
System.out.printf(" Is on loan?: %1$s\n", bIsOnLoan ? "yes" : "no");
System.out.printf(" Cost: %1$d\n", iCost);
System.out.printf(" Weight: %1$d\n", iWeight);
System.out.printf(" Is rechargeable?: %1$s\n", bIsRechargeable ? "yes" : "no");
System.out.printf(" Power source: %1$s\n", strPowerSrc);
Tool t = new Tool();
// do something with data here
this.storeTool(t);
}
} else {
System.out.printf("Line skipped: \"%1$s\"\n", lineOfText);
}
}
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
} else {
System.out.println("No file selected");
}
}
The Apache Commons CSV library is nice for reading delimited data. Here is a short intro if you're interested.