0

I have a directory with text files, those files contain a number in every line, which I have to do some calculations with. I need to read a file, read every single line in the file and then continue with another file until they all are read. I am new to Java so I was thinking of using scanner to read every line, but I haven't been able to get a file from a directory correctly.

private String Folder_path = "the path to dir";
Path kazkas = Paths.get(Folder_path);
File[] files = new File(Folder_path).listFiles();

I get to this point, but haven't found a solution how to take single file and pass it to the scanner.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Ausrys
  • 9
  • 4
  • This is an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). The purpose of the [Scanner](https://www.w3schools.com/java/java_user_input.asp) class is to get user input, not read files. These are two very different tasks. – Jesse Oct 17 '22 at 16:35
  • Does this answer your question? [Reading a plain text file in Java](https://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java) – Jesse Oct 17 '22 at 16:36
  • You can use [`Files.lines(Path)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Files.html#lines(java.nio.file.Path)) or [`Files.lines(Path, Charset)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Files.html#lines(java.nio.file.Path,java.nio.charset.Charset)). There is no need to use `Scanner` if you just want to read lines. – Mark Rotteveel Oct 17 '22 at 16:38
  • You can use Scanner if you want to. You would need a loop that new a new scanner for each file and then use the scanner to reads the lines. – Cheng Thao Oct 17 '22 at 16:44
  • Reading from a single file is not a problem for me, a problem for me is that when I try for example pass: `File[] files = new File(Folder_path).listFiles() ` `Files.lines(files[1])` or any other reader I fail – Ausrys Oct 17 '22 at 17:06

1 Answers1

0

My solution:

private String Folder_path = "the_path_to_fikes";
File[] files = new File(Folder_path).listFiles();
String obj = files[1].toString();
    Path path = Paths.get(obj);
    try {
        Files.lines(path).forEach(line -> {
            System.out.println(line);
        });
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Ausrys
  • 9
  • 4
  • 1
    Fine but you'd get a nasty surprise if one of those files is a directory ;) – g00se Oct 17 '22 at 22:39
  • yes, but for my task I knew that there were only files in that directory, in another cases I believe there should be a check to see if it is a file or directory – Ausrys Oct 18 '22 at 13:15