gpt4 book ai didi

java - 需要帮助解决 FileOutputStream 和 DataOutputStream 上的 IOException

转载 作者:行者123 更新时间:2023-12-01 22:56:49 25 4
gpt4 key购买 nike

我试图将整数写入文本文件作为保存游戏的方法,但我同时收到 IOException 和 FileNotFound 异常(写在它们出现的行的注释中)。 saveData类存储的是字符统计数据,它们都是整数。我应该怎么做才能修复异常?

Scanner s = new Scanner(System.in);
Character player = new Character();

System.out.print("Enter your username: ");
String user = s.nextLine();
System.out.print("Give a name to the file: ");
String filename = s.nextLine();
s.close();

Vector<Integer> saveData = new Vector<Integer>();
saveData.add(player.Int);
saveData.add(player.Vit);
saveData.add(player.Str);
saveData.add(player.Dex);

FileOutputStream fos = new FileOutputStream("C:\\Users\\" + user + "\\" + filename + ".csv"); //Unhandled exception type FileNotFoundException
DataOutputStream dos = new DataOutputStream(fos);

for(int i = 0; i < saveData.size(); i++) {
dos.writeInt(saveData.get(i)); //Unhandled exception type IOException
}

dos.close(); //Unhandled exception type IOException

最佳答案

如果您的user目录不存在,您将收到该异常。应该使用 user.name 来获取当前登录的用户名,而不是询问

尝试以下操作:

String user = System.getProperty("user.name"); //get the current logged in user name

Path path = Paths.get("C:\\Users\\" + user + "\\" + filename + ".csv");

//Try-with-resource will close DOS even upon exception
try(DataOutputStream dos = new DataOutputStream(Files.newOutputStream(path)) {
for(int i = 0; i < saveData.size(); i++) {
dos.writeInt(saveData.get(i));
}
} catch (IOException ex) {
ex.printStackTrace();
}

关于java - 需要帮助解决 FileOutputStream 和 DataOutputStream 上的 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58436468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com