简体   繁体   English

写入jar文件中的文本文件

[英]Writing to a text file within a jar file

I was recently trying to export my game to a jar file, and I ran into a problem with converting files to input and output streams. 我最近试图将我的游戏导出到jar文件中,但在将文件转换为输入和输出流时遇到问题。 With the regular code that was not exported, I was able to read and write to text files by simply calling the Scanner and PrintStream constructor with the File location. 使用未导出的常规代码,我只需在File位置调用Scanner和PrintStream构造函数即可读取和写入文本文件。 This didn't work inside the jar because apparently these were no longer considered as files. 这在jar内不起作用,因为显然这些不再被视为文件。 I was able to work around the input stream one by doing this: 通过执行以下操作,我能够解决输入流:

Scanner infile = new Scanner(this.getClass().getResourceAsStream("Resources/leaderboard.txt"));

as opposed to, 相对于

Scanner infile = new Scanner("Resources/leaderboard.txt");

And I am trying to utilize PrintStream, but so far I have not found an equivalent function that will take in a String location and return an OutputStream for the PrintStream constructor. 而且我正在尝试利用PrintStream,但是到目前为止,我还没有找到一个等效的函数,该函数将在String位置并为PrintStream构造函数返回OutputStream。 Should I use a different method for writing to text files in a jar, is there a function or method of converting it to an OutputStream that I have yet to see, or should I avoid printing to a text file altogether? 我应该使用其他方法来写入jar中的文本文件吗,是否存在将其转换为尚不可见的OutputStream的函数或方法,还是应该避免完全打印到文本文件? Thanks in advance. 提前致谢。

You shouldn't and for practical purposes can't write to a "file" within a jar file. 出于实用目的,您不应这样做,也不能将其写入jar文件中的“文件”。 Yes, there are kludges that allow you to get around this, but they shouldn't be implemented. 是的,有一些让您绕开这一难题的方法,但不应实施这些方法。 Instead all files that the program might change should be outside of the jar and should be separate files. 相反,程序可能会更改的所有文件都应该在jar之外,并且应该是单独的文件。

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

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