0

On Java Ive make a simple program with search bar. Ive also a CSV File 'file.csv' that contains this:

"ID","FIRSTNAME","LASTNAME"
"JM1","Jean","Martial"
"AD1","Audrey","Dubois"
"BX1","Bertrand","Xavier"

I can open the file on Java with this line.

String file = "C:\\file.csv";

To verify if file exists I use this line.

if(new File(file).exists()) {
    JOptionPane.showMessageDialog(frame, "Fichier ouvert succes");
}

Now I want to parse the file to extract AD1 and display true if exist or false if not exists. Ive declared Scanner for this, but i dont know how to setup for this.

Scanner scanner = null;
try {
  scanner = new Scanner(new File(file));
  scanner.useDelimiter(coma_delimiter);
  while(scanner.hasNext()) {
    String s1= scanner.next();
    System.out.print(s1 +"   ");
    if(s1.equals(search_field.getText())) {
      System.out.print("OKOK");
    } else {
      System.out.println("NOK");
    }
  }


} catch (FileNotFoundException fe) {
  fe.printStackTrace();
} finally {
  scanner.close();
}

Here the search_field is a JTextField.

1
  • "I can open the file on Java with this line. String file = "C:\\file.csv";" - no, that is just a string and doesn't open the file at all. Besides that, if you are able to read the file line by line then what's the problem with checking whether the line contains ADB1? (Note that you don't want to check using equals() but contains()). If you need to do more then it might be better to look for a CSV parser library and use that. Commented Nov 17, 2017 at 9:41

3 Answers 3

1

You are not reading your file line by line. What you are actually supposed to do is get a line, split it, remove the double quotes and compare to your string. Or you can wrap your input string in a double quote and just compare with the string after splitting. For this try the following code:

Scanner scanner = null;
try {
  scanner = new Scanner(new File(file));

  String s1 = null;
  String id= null;
  String[] tempArr = null;
  String searchStr = "\""+search_field.getText()+"\"";
  System.out.print("searchStr = " + searchStr );

  while(scanner.hasNext()) { // While there are more lines in file 
    s1= scanner.nextLine();
    tempArr = s1.split(","); // use coma_delimiter instead coma_delimiter if coma_delimiter=","
    id = (tempArr != null && tempArr.length > 0? tempArr[0] : null);
    System.out.print("ID = " + id);

    if(id != null && id.equals(searchStr)) {
      System.out.print("OKOK");
      break; // quit the loop searchStr is found
    } else {
    System.out.println("NOK");
    }
  }
} catch (FileNotFoundException fe) {
 fe.printStackTrace();
} finally {
  scanner.close();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, your script works. Ive changed you System.out.println by Alert message. And when I verify "BX1" exists. Ive 4 alert. The three beginning alert are FALSE and the fourth is TRUE. How to get directly TRUE on the first ALERT if its true. And FALSE directly if its FALSE
I just added id != null && in the if condition as id can be null. This is to avoid null pointer exception.
0

You may want to use Apache Commons CSV instead as this is designed to work with csv file, straight from their page is the below example

Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
    String lastName = record.get("Last Name");
    String firstName = record.get("First Name");
}

where "Last Name" and "First Name" are all column names. This way you can clearly check on which column your string is.

Maven dependency below:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.5</version>
</dependency>

2 Comments

I can't import CSVRecord and CSVFormat. Why? please.
If you are using maven i have included the dependency on my answer else you need to download the jar file in their site
0

You could also use the stream API to process each line individually. It may also have methods that would make this more elegant than my answer.

final String ENCL = "\"";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    Map<String, List<String>> ans = stream.map(s -> {
        String[] split = s.split(",");
        if(split.length > 2) {
            for(int i = 0; i < split.length; ++i) {
                if(split[i].length() >= 2) {
                    if(split[i].startsWith(ENCL)) {
                        split[i] = split[i].substring(1);
                    }
                    if(split[i].endsWith(ENCL)) {
                        split[i] = split[i].substring(0, split[i].length()-1);
                    }
                }
            }
        }
        return split;
    })
    .filter(s->s.length > 2)
    .collect(Collectors.toMap(s -> s[0], s-> Arrays.asList(s[1], s[2])));

    // do what you will with ans
    return ans.containsKey("AD1");
}
catch(IOException ex) {
    // do what you will
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.