0

My code use getClass().getResource() to get the file location but when I create the jar file it can't find my file even I copy the to jar file directory.

And the log give me a weird path Server2018.jar!\com\company\party.txt It has the "!" after the jar file name.

java.io.FileNotFoundException: file:\C:\Users\baram\IdeaProjects\Server2018\out\artifacts\Server2018_jar\Server2018.jar!\com\company\party.txt (The filename, directory name, or volume label syntax is incorrect)
        at java.base/java.io.FileInputStream.open0(Native Method)
        at java.base/java.io.FileInputStream.open(Unknown Source)
        at java.base/java.io.FileInputStream.<init>(Unknown Source)
        at java.base/java.io.FileReader.<init>(Unknown Source)
        at com.company.FileManager.getVote(FileManager.java:285)
        at com.company.PieParty.createScene(PieParty.java:74)
        at com.company.PieParty.initFx(PieParty.java:58)
        at com.company.PieParty.access$100(PieParty.java:21)
        at com.company.PieParty$1.run(PieParty.java:48)
        at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$9(Unknown Source)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(Unknown Source)
        at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
        at java.base/java.lang.Thread.run(Unknown Source)

This is what I use. Is there a better way to done this?

URL pty = getClass().getResource("party.txt");
File file = new File(pty.getPath());
reader = new BufferedReader(new FileReader(file));
Scanner sc = new Scanner(reader);
BAXMAY
  • 61
  • 6
  • 3
    You could use getResourceAsStream for short. – Beri May 09 '18 at 17:01
  • URL.getPath() *does not* convert a URL to a file name. It just returns the path portion of the URL, which is not guaranteed to be a valid file name. As others have pointed out, you don’t need a File just to obtain an InputStream from a resource. – VGR May 09 '18 at 18:24

2 Answers2

1

Use

Scanner sc = new Scanner(ClassLoader.getSystemResourceAsStream("party.txt"));

Then you will not get FileNotFoundException after exporting to jar

Umer Farooq
  • 762
  • 1
  • 8
  • 17
-1

Try the following:

File file = new File(getClass().getClassLoader().getResource("relative/path/to/file/from/resources/dir").getPath());
reader = new BufferedReader(new FileReader(file));

I'm going to assume you have properly placed your file in the resources directory.

Pubudu
  • 964
  • 1
  • 7
  • 17
  • The question code fails because the "resource" is not a file on the file system. Your answer fails for the same reason. – Andreas May 09 '18 at 17:46