将类对象从一个正在运行的jar文件写入另一个目录中的文件



基本上,我的程序在启动时从内存文件中的类对象读取参数,如果在运行的程序中更改了参数,它会覆盖内存文件并再次从中读取以更新参数。

我的应用程序在IDE中正常工作。然后,我从IDE构建了我的第一个jar,并从批处理文件中运行它,它可以工作,但并不像预期的那样。

如果内存文件存在,则在程序启动时它是reed,没有问题。

但是,当我尝试更改程序参数或在没有内存文件的情况下启动程序时,它应该用更新的类对象alt覆盖内存文件。create a new,它返回";FileNotFoundException";。

这是我的业余代码,我创建了一个类,目的是编写/阅读一个";SaveClass";文本文件的对象:

public class ManageMemory {
//filepath
private String MEMORY_DIR = new StringBuffer(System.getProperty("user.home"))
.append("\Documents\memory.txt").toString();
private File targetFile = new File (MEMORY_DIR);
//writes selected object to txt-file" with exceptions included
public void writeToMemory(SaveClass object) {
try {
FileOutputStream f = new FileOutputStream(MEMORY_DIR);
ObjectOutputStream o = new ObjectOutputStream(f);
//write object to file
o.writeObject(object);
o.close();
f.close();
} catch (FileNotFoundException e) {
System.out.println("File not found while writing");
} catch (IOException e) {
System.out.println("Error initializing stream");
}
}
//reads current object in memory directory
public SaveClass readFromMemory() {
SaveClass inMemory = new SaveClass();
if (!targetFile.exists()) {
writeToMemory(inMemory);
}
try {
FileInputStream f = new FileInputStream(MEMORY_DIR);
ObjectInputStream o = new ObjectInputStream(f);
inMemory = (SaveClass) o.readObject();
} catch (FileNotFoundException e) {
System.out.println("File not found while reading");
} catch (IOException e) {
System.out.println("Error initializing stream");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inMemory;
}
}

我搜索了关于如何处理我的问题的信息,但没有找到多少我能理解的。在运行.jar程序时,我测试了在保存文件上打印canWrite((,结果返回true。

了解实际情况的最佳方法是通过以下步骤:

  • 用更新的Path类替换java.io.File的所有用法
  • 将FileOutputStream的所有用法替换为Files.newOutputStream
  • 确保每个catch块都打印一个堆栈跟踪

java.io.File是一个非常古老的类。它有很多设计缺陷,仅仅是因为API的设计在1995年没有得到很好的理解。

但是java.nio.file包更现代,可以纠正所有这些问题。它还有更详细、信息更丰富的例外情况。

使用该软件包看起来非常相似:

public void writeToMemory(SaveClass object) {
try (ObjectOutputStream o = new ObjectOutputStream(
Files.newOutputStream(
Paths.get(MEMORY_DIR)))) {
//write object to file
o.writeObject(object);
} catch (IOException e) {
System.out.println("Error initializing stream");
e.printStackTrace();
}
}

这将打印一个异常,该异常准确解释了无法写入文件的原因。

(请注意,我使用的是try-with-resources语句——也就是说,ObjectOutputStream创建位于try后面的括号内——它将自动关闭ObjectOutputStream,进而关闭底层OutputStream。(

最新更新