简体   繁体   English

如何在netbeans build jar文件中访问txt文件?

[英]How to acces txt file in netbeans build jar file?

So currently my netbeans project folders looks like this: 所以目前我的netbeans项目文件夹如下所示:

  • Block_Breaker <--Project Block_Breaker < - 项目
    • build 建立
    • dist DIST
      • Block_Breaker.jar Block_Breaker.jar
    • nbproject nbproject文件
    • src SRC
      • packageONE packageONE
      • packageTWO packageTWO
        • data.txt data.txt中
    • manifest.mf MANIFEST.MF
    • applet.policy applet.policy
    • build.xml 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). 我想知道如何访问packageTWO中的data.txt文件(当我通过jar文件而不是netbeans运行Block_Breaker时)。 Normally if run through netbeans the following code will work: 通常,如果通过netbeans运行,以下代码将起作用:

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. 但是,如果我运行一个netbeans创建的jar文件,它不起作用。

You can't write to that file once it is packaged into a jar file. 将文件打包到jar文件后,您无法写入该文件。

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. 女巫为您提供了一个可以用来检索文件内容的InputStream女巫。

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. 如果您需要访问该文件,那么最简单的方法不是将其打包到jar中,而是将其独立放在文件系统的某个位置。

More infos about getResourceAstream in the javadoc 有关javadoc中 getResourceAstream更多信息

This is because your .jar file does not include a folder named src/ 这是因为.jar文件不包含名为src/的文件夹

Please use ClassLoader.getResource to load resources. 请使用ClassLoader.getResource加载资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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