Java does not receive a file in source code at compilation

I recently had a problem with Java. I tried some things that I found on the Internet, but they did not work, so I need help. I have a Java project in Eclipse. My main class is in src/programCode/UI_Main2.java. In this .javaI am trying to access the file insrc/files/File.file

And this is when things are strange.

  • If I use /src/files/File.file, he gives me NoSuchFileException.

  • If I use src/files/File.file, it works in Eclipse, but when I compile it into an .jar executable, it gives me NoSuchFileException.

  • If I use /files/File.file, he gives me NoSuchFileException.

  • If I use files/File.file, he gives me NoSuchFileException.

  • If I use files/File.file, he gives me NoSuchFileException.

  • If I use this.getClass().getResource("/files/File.file").getPath().substring(1)(without a substring, it gives me an invalid character), it gives me NoSuchFileException(but it shows me the absolute path, and the file exists there!)

  • If I use this.getClass().getResource("files/File.file").getPath(), it gives me NullPointerException, and the program crashes.

  • If I use this.getClass().getResource("src/files/File.file").getPath(), it gives me NullPointerException, and the program crashes.

  • If I use this.getClass().getResource("/src/files/File.file").getPath(), it gives me NullPointerExceptionand the program will work.

So, I do not know what to do. src/files/File.file- the only one that works, but it does not compile into an executable jar. So please help me, I haven't found a solution yet. Thank!

+4
source share
2 answers

A file search depends on two things:

  • Do you use absolute or relative path
  • Where is your working directory

Unix- , /dir1/dir2/file, , , .

, / .

:

"If I use src/files/File.file it works in Eclipse but when I compile it to a executable .jar it gives me NoSuchFileException." 

Eclipse src ( ), .

.jar - . .jar src, .

, src ( Resurces - ), .jar.

.jar:

Jar

.jar, :

http://www.cefns.nau.edu/~edo/Classes/CS477_WWW/Docs/pack_resources_in_jar.html

+3

, , , .

<Eclipse workspace location>\<project name>\<file location in project>
+1

All Articles