我使用文件编写器以一种类似CSV的格式将对象的arraylist写为文件,作为字符串。无论如何,我有问题让它工作,但现在我得到一个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);
}
答案 0 :(得分:2)
尝试使用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 */
答案 1 :(得分:1)
每次要重写时都可以尝试删除文件。 尝试{
File file = new File("PeopleDetailsFile");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
或者:您可以将FileWriter设置为它附加到当前文档的位置:
FileWriter writer_file = new FileWriter("PeopleDetailsFile", true); //true means append = true;
答案 2 :(得分:1)
使用fileName
和List
作为参数调用此方法。
public void fileWrite(String fileName,ArrayList<PeopleDetails> person){
File f ;
FileWriter fw = null;
BufferedWriter bw = null;
try {
f = new File(fileName);
fw = new FileWriter(f.getAbsoluteFile());
bw = new BufferedWriter(fw);
for(PeopleDetails i:person){
bw.write(i.name+","+i.number+";");
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(bw!=null)
bw.close();
if(fw!=null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 3 :(得分:0)
使用附加标志的FileWriter的其他构造函数:FileWriter(文件文件,布尔附加)
答案 4 :(得分:0)
您可能正在尝试写入“root”文件夹。您应该按照Android上下文openFileOutput而不是FileWriter
来写入应用程序的目录(而不是根目录)。
根据文件:
打开与此Context的应用程序包关联的私有文件 写作。如果文件尚不存在,则创建该文件。