gpt4 book ai didi

java - Filewriter 创建一个只读文件

转载 作者:行者123 更新时间:2023-12-01 18:38:18 28 4
gpt4 key购买 nike

我使用文件编写器以类似 CSV 的格式将对象数组列表作为字符串写入文件。不管怎样,我在让它工作时遇到了问题,但现在我收到一个 FileNotFound 异常,它说创建的文件在异常中是只读的。正如我检查的那样,该文件已创建,但显然无法写入。然而,我实际上想覆盖内容,但出现此错误。

        ///Like a CSV file. 
try{
FileWriter writer_file = new FileWriter("PeopleDetailsFile");

String filestring = ""; ///initializes filestring, which is written to the file.
for(PeopleDetails person : peopledetails_file){
String person_detail_string = "";
person_detail_string = person.name + "," + person.number;
filestring = filestring + person_detail_string + ";";

}
writer_file.write(filestring);
writer_file.close();
}
catch (IOException e) {
Log.e("ERROR", e.toString());

}finally{
///Hopefully won't get an error here.
Intent switch_menu = new Intent(this, MenuList.class);
startActivity(switch_menu);
}

最佳答案

尝试使用PrintWriter。我在下面为您提供一些简短的指导方针,但需要进行修改。此外,请注意,我将姓名和号码保存在不同的行中,因此当您阅读详细信息时,您应该使用相同的方法。

 public void writeToFile(String fileName, ArrayList<PeopleDetails> peopledetails) {
try {
/*
* Create a FileWriter object that handles the low-level details of
* writing
*/
FileWriter theFile = new FileWriter(fileName);

/* Create a PrintWriter object to wrap around the FileWriter object */
/* This allows the use of high-level methods like println */
PrintWriter fileOut = new PrintWriter(theFile);

/* Print some lines to the file using the println method */
for (int i = 0; i < peopledetails.size(); i++) {
fileOut.println(peopledetails.get(i).getName());
fileOut.println(peopledetails.get(i).getNumber());
}
/* Close the file so that it is no longer accessible to the program */
fileOut.close();
}

/* Handle the exception thrown by the FileWriter methods */
catch (IOException e) {
System.out.println("Problem writing to the file");
}
} /* End of method writeToFile */

关于java - Filewriter 创建一个只读文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20890980/

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