简体   繁体   中英

How to acces txt file in netbeans build jar file?

So currently my netbeans project folders looks like this:

  • Block_Breaker <--Project
    • build
    • dist
      • Block_Breaker.jar
    • nbproject
    • src
      • packageONE
      • packageTWO
        • data.txt
    • manifest.mf
    • applet.policy
    • build.xml

I want to know how can i acces a data.txt file in packageTWO(when i run Block_Breaker through a jar file and not netbeans). Normally if run through netbeans the following code will work:

FileWriter x=new FileWriter("src/packageTWO/data.txt");

PrintWriter pr=new PrintWriter(x);

But if i run a jar file that netbeans created it doesnt work.

You can't write to that file once it is packaged into a jar file.

Yet reading is still possible using one of the following:

<YourClass>.class.getClassLoader().getResourceAsStream("packageTWO/data.txt");
// or
this.getClass().getResourceAsStream("/packageTWO/data.txt");

witch gives you an InputStream witch you can use to retrieve the content of the file.

If you are required to wite to that file then the simplest way is not to pack it into the jar but have it standalone some where on the filesystem.

More infos about getResourceAstream in the javadoc

This is because your .jar file does not include a folder named src/

Please use ClassLoader.getResource to load resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM