1

I've been trying to read the text file in my java projects, I've been looking for the solution for the whole day, I've tried loads of methods but none of them have worked. Some of them: (Also, I have to use File and Scanner class)

String file = "fileTest.txt";
var path = Paths.get("test", file);
System.out.println(path);
System.out.println(Files.readString(path));

Exception in thread "main" java.nio.file.NoSuchFileException: test\fileTest.txt

    URL url = ClassLoader.class.getResource("fileTest.txt");
    File file = null;
    file = new File(url.toURI());
    Scanner scanner = new Scanner(file);
    scanner.useDelimiter(" ");

    while(scanner.hasNext()) {
        System.out.println(scanner.toString());
    }

Exception in thread "main" java.lang.NullPointerException

    File file = new File("../test/fileTest.txt");
    Scanner scanner = new Scanner(file);
    scanner.useDelimiter(" ");

    while(scanner.hasNext()) {
        System.out.println(scanner.toString());
    }

    scanner.close();

Exception in thread "main" java.io.FileNotFoundException: ..\test\fileTest.txt (The system cannot find the path specified)

enter image description here

4 Answers4

4

The problems here are project structure and how you're trying to locate that file. Conventionally, your java class files should exist within the directory src/main/java and your resource files should exist within src/main/resources. If you follow this convention, you can obtain the resource with a ClassLoader.

        try (InputStream input = getClass().getClassLoader().getResourceAsStream("test.txt");
             Scanner scanner = new Scanner(Objects.requireNonNull(input)).useDelimiter(" ")) {
            while(scanner.hasNext()) {
                System.out.println(scanner.toString());
            }
        } catch (IOException ioe) {
            throw new RuntimeException("Something went wrong scanning file!", ioe);
        }
Jason
  • 5,154
  • 2
  • 12
  • 22
3

All of the answers talking about relative paths are going to work or not work depending on what your working directory is when you are running your program. If you truly want your file to live inside the classpath, what you want to do is use it as a resource and look on how to load resources at runtime. If, on the other hand, you want to treat it just like any other file, you will need to know what the working directory is at runtime if you expect any relative pathing to work, or have the absolute path specified at some known place, like a configuration file.

Omaha
  • 2,262
  • 15
  • 18
1

Reading a file with BufferReader, using try-with-resource which automatically closes the resources when processing has terminated.

See info on Java try-with-resource: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Edit: Ensure you have included the folder as a resource in your build path. How do I add a resources folder to my Java project in Eclipse

String inputFile = "test/fileTest.txt";
List<String> lines = new ArrayList<>();

try(BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile))) {

    String line = bufferedReader.readLine();

    while(line != null){
        lines.add(line);
        line = bufferedReader.readLine();
    }

} catch (IOException e) {
    e.printStackTrace();
}
Bradley
  • 327
  • 2
  • 11
0

Replace

File file = new File("../test/fileTest.txt");
Scanner scanner = new Scanner(file);

with

File file = new File("test/fileTest.txt");
Scanner scanner = new Scanner(file);

Then, if you want to confirm it, just do the following:

System.out.println(file.exists());

Also, replace

while(scanner.hasNext()) {
    System.out.println(scanner.toString());
}

with

while(scanner.hasNext()) {
    System.out.println(scanner.next());
}

because scanner.toString() can not be used to get an input; it should be scanner.next().

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • I tried that as well, Exception in thread "main" java.io.FileNotFoundException: test\fileTest.txt (The system cannot find the file specified) – curiousStudents May 19 '20 at 14:03
  • @curiousStudents - Try it once again. I'm sure you must have done some other mistake in your last attempt. I tested my code before posting the answer. – Arvind Kumar Avinash May 19 '20 at 14:05
  • @curiousStudents - You haven't still replaced `scanner.toString()` with `scanner.next()`. Also, are you sure your file name has `.txt` extension? I suggest you backup the content of the file somewhere, delete the file and create a new file, `fileTest.txt` in this location and restore the content from the backup. – Arvind Kumar Avinash May 19 '20 at 14:11
  • Yeah, thanks, I created a text file, but it was not saved with .txt extension but just as a "File" – curiousStudents May 19 '20 at 14:17