Hello!

Faced a problem: when running code from under Eclipse, the code works fine, but after exporting to jar, File.canRead () and sanWrite () return false, which causes the program to fail, although the file exists (Created in the environment and not deleted anywhere) .

Problem file initialization code:

static File data = new File("data/data.txt"); data.setWritable(true, true); data.setReadable(true, true); if(!data.canRead() || !data.canWrite()){ JOptionPane.showMessageDialog(null, "Error file! Read: " + data.canRead() + " Write: " + data.canWrite() + " Patch: " + data.getAbsolutePath()); return; } 

Content Manifest.ML:

 Manifest-Version: 1.0 Class-Path: . Main-Class: ua.com.swgroup.homechat.homechat Application-Name: HomeChat Permissions: all-permissions 

Export order on 1 screen. Window after launching on 2 screen.

PS: Also, after exporting, a mass of left classes is created, I will be glad if you explain why they are created (In the main method there are enums with ClientID, ImageType, MessagePosition) - made the screen at number 3.

All screenshots: http://imgur.com/a/CfT0I

  • Where does the file lie at startup time in Eclipse? And where during the launch as a jar? Or should it be inside the jar? - Riĥard Brugekĥaim
  • It is inside the jar in the data / data.txt folder - VladimirSW

1 answer 1

The bottom line is that he searches for a folder and a file in it NEXT with a jar. In order to access the files inside the jar, you need to get a little dirty:

 new File(getClass().getResource("data/data.txt").getPatch()); 

Moreover, such a construction cannot be called up in the static method !

For an absolute address, you must write starting with "/"

 .getResource("/com/abc/package/resources/"); 
  • data = new File(getClass().getResource("data/data.txt")); - throws away The constructor File (URL) is underfined. If I add getPatch (), it compiles fine, but the problem is: getPatch () returns the path already in the package next to the class, or in the root jar? PS: the method is not static. - VladimirSW
  • I warned about not static, but added an absolute address about the information in the response. - Riĥard Brugekĥaim
  • Something I’m drowning and dumbing .... imgur.com/9d4OBNj - dropped the hierarchy - VladimirSW
  • Better make a folder in src - Riĥard Brugekĥaim
  • imgur.com/Jhghpic - I made it this way, but when I start it (and through ifpar and through jar) again an old error that you cannot read / write. I tried to go through "Patch:" + data.getAbsolutePath () "- there is a file, after the export the path is also correctly displayed. - VladimirSW