-2
String path = "C:" + File.separator + "testFolder" + File.separator + "one.txt";
Scanner sc = new Scanner(path);
while (sc.hasNextLine()) {
    System.out.println(sc.nextLine());//prints C:\testFolder\one.txt once
}

Edit: My file one.txt contains 3 lines of text I would like java to loop through all the lines and print me those three lines. But I only get "C:\testFolder\one.txt" printed on the console once only with this code.

This seems to happen only when i am using file.separator for the file path, if I use C:\\testFolder\\one.txt or C:/testFolder/one.txt for file path it loops through the file and reads the file with all three lines. What can be done to read the whole file with the File.separator?

Ami
  • 61
  • 9
  • 1
    please check https://stackoverflow.com/a/13185765 – Jaydeep Devda Nov 29 '22 at 05:42
  • What output do you get, and what do you expect? – tgdavies Nov 29 '22 at 05:45
  • 1
    Does this answer your question? [Reading a .txt file using Scanner class in Java](https://stackoverflow.com/questions/13185727/reading-a-txt-file-using-scanner-class-in-java) – Silvio Mayolo Nov 29 '22 at 05:49
  • 1
    Refer to documentation for [Scanner](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Scanner.html#%3Cinit%3E(java.lang.String)). You are calling wrong constructor. Also refer to [Reading a plain text file in Java](https://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java) – Abra Nov 29 '22 at 05:56
  • `= new Scanner (Paths.get("C:", "testFolder", "one.txt"))` is what you need – g00se Nov 29 '22 at 10:00

1 Answers1

1

You are using Scanner(String source) constructor, but you probably want to use Scanner(File source) constructor. Try:

Scanner sc = new Scanner(new File(path));
Pekinek
  • 298
  • 1
  • 9
  • Your answer is essentially the same as my [comment](https://stackoverflow.com/questions/74609577/how-to-read-a-file-with-file-separator-in-java#comment131696291_74609577). I would also like to think that the OP could ascertain how to fix his code by looking at both the documentation and the other SO question that I linked to in that comment. – Abra Nov 29 '22 at 06:52
  • String path = "C:" + File.separator + "testFolder" + File.separator + "one.txt"; System.out.println(path); //FileInputStream fis = new FileInputStream(); Scanner sc = new Scanner(new File(path)); while (sc.hasNextLine()) { System.out.println(sc.nextLine()); //prints nothing in the console } this doesn't seem to work as it prints nothing int he console, previously it printed the path. – Ami Nov 29 '22 at 06:53