我需要将一个文本文件放入 jar 中。当用户运行 jar 时,将出现登录屏幕。一旦他登录并验证了自己的身份,就会出现一个文本文件,他应该能够在其中写入并保存。我已经完成了登录和身份验证部分,任何人都可以帮助我仅对打开文本文件并且用户有权写入并保存它的部分进行编码吗?
最佳答案
您可以这样做,但不要直接修改文件。如果由于某种原因写入修改内容失败,您将丢失原始文件和修改后的文件。
创建一个临时文件,将修改后的内容放入其中,然后才替换原始文件。
示例:
final Map<String, String> = Collections.emptyMap();
final URI zip = URI.create("jar:file:/path/to/your/jar");
final FileSystem zipfs = FileSystems.newFileSystem(zip, env);
final Path tempFile = Files.createTempFile("tmp", "txt");
final Path srcfile = zipfs.getPath("path/of/file/into/jar");
final Path renamed = srcfile.resolveSibling("newfile");
// read contents of source file, for instance Files.newBufferedReader(), or
// Files.readAllLines(); then write the modified content into tempFile; and
// when done:
Files.copy(tempFile, renamed);
Files.delete(tempFile);
Files.move(renamed, srcfile, StandardCopyOption.REPLACE_EXISTING);
zipfs.close(); // <-- don't forget that
请注意,重命名为原始文件是最后操作。
关于java - 用户可以打开 jar 内的文本文件并对其进行更改吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22694623/