-1

I found this file exist in the url showed, but still get NoSuchFileException. Had try many way but the path return always same, but cant read the file. How it will be? It there but not there? why plz?

 public void readFile() throws IOException {
  
    String fileName = "domain.txt";
    ClassLoader classLoader = getClass().getClassLoader();

    File file = new File(classLoader.getResource(fileName).getFile());

    //File is found
    System.out.println("File Found : " + file.exists());

    //Read File Content
    String content = new String(Files.readAllBytes(file.toPath()));
    System.out.println(content);
}

enter image description here

VendettaV
  • 67
  • 2
  • 7
  • Have you tried something like this: https://stackoverflow.com/questions/3888226/how-can-i-read-file-from-classes-directory-in-my-war ? And, by the way, you should never post your code as a picture. Paste the code and the output to the question itself, so we can copy it. – default locale Aug 14 '20 at 04:15
  • 3
    A resource is not a file. You need to use `Class.getResource()` and friends, not a file. Don't post pictures of text here. Post the text. – user207421 Aug 14 '20 at 04:15
  • @MarquisofLorne sorry, i had edited. But how when i use Class classer = getClass(); URL url = class.getResource("domain.txt"); i get null – VendettaV Aug 14 '20 at 06:38
  • Don't call `getFile()`, or create a `File`, or the rest of it. `ClassLoader.getResource()` returns a `URL`: get the input stream directly from that. – user207421 Aug 14 '20 at 07:37

1 Answers1

0

When you use ClassLoader you must use absolute path

public void readFile() throws IOException {

    // Must use absolute path here, so start with a slash
    String fileName = "/domain.txt";

    // Use InputStream instead of File
    InputStream input = ClassLoader.getSystemResourceAsStream(filename);
    BufferedReader bf = new BufferedReader(new InputStreamReader(input));

    String line = null;
    StringBuilder sb = new StringBuilder();
    while ((line = bf.readLine()) != null) {
        sb.append(line);
    }

    System.out.println(sb.toString());

    System.out.println(content);
}
J.Adler
  • 1,303
  • 11
  • 19