-2

I have an input file data, name input.dat which is stored in the src/main/resources. When I tried to read from this input file as follows:

String[] lines = Files.readAllLines(new File("input.dat").toPath()).toArray(new String[0]);

I received the following exception:

java.nio.file.NoSuchFileException: input.dat

Can anyone help me with what did I do wrong here? Thank you in advance!

javabrett
  • 7,020
  • 4
  • 51
  • 73
Soe
  • 45
  • 1
  • 8

2 Answers2

0

The java file you are running is probably not in the same directory as the file input.dat.

When referencing the file in your Java code include the relative path to it. If the java file that you are running is in src/main then the relative path would be resources/input.dat.

In that case, your code would look like this:

String[] lines = Files.readAllLines(new File("resources/input.dat").toPath()).toArray(new String[0]);

Hope this helped you and if you have any further questions please feel free to post a comment below!

Micheal O'Dwyer
  • 1,237
  • 1
  • 16
  • 26
  • Hi Michael, thank for your help, I had to replace the whole part as new File("src/main/resources/input.dat") then it worked. But I have a question, when I run as Java Application then it works fine, but if I build the jar file with maven, then run this jar file, then it has again the NoSuchFileException. Do you have idea why it happened? – Soe Jan 21 '18 at 20:44
  • Yes, that is a very common problem. It can be caused by many issues. Perhaps the file is not properly included in the build system or in the classpath. – Micheal O'Dwyer Jan 21 '18 at 20:47
  • That's not the best solution. Obviously, he's using Maven, thus, the way to go is to use the classloader: `getClass().getClassLoader().getResource("input.dat")` – UninformedUser Jan 21 '18 at 20:55
  • Unfortunately, I am not too familiar with Maven. If you feel that it is necessary to include that solution then post your own answer. – Micheal O'Dwyer Jan 21 '18 at 21:02
  • @AKSW hi AKSW, can you please explain me how this solution work? Thank you – Soe Jan 21 '18 at 21:09
  • @Soe Some developers believe that the Maven directory structure will be replicated in the .jar after compilation. Therefore, they are tempted to try to open the data resource with a strategy similar to yours. In other words, they believe they have to handle the Maven directory structure themselves, including the absolute path to the current .jar location. This does not work. First, one must keep in mind that Maven does not "push" its directory structure in .jars. – UninformedUser Jan 22 '18 at 00:43
  • @Soe Those folder `src/main/java`, `src/main/resources`, etc. are just convention, please simply look at the jar file generated once you called `mvn package` – UninformedUser Jan 22 '18 at 00:43
0

Replace input.dat with the exact path of input.dat. Such as C:/Users/Soe/Desktop/input.dat

anL
  • 1,073
  • 1
  • 11
  • 31