[英]File Read and Write
每当文本字段中有一个条目时,我都有一个用于写入文件的代码。 但是在此过程之后,当再次输入条目时,文件将被重写,而不是继续输入文件,因此我丢失了之前的数据。 我如何重写现有数据,以便即使关闭应用程序后也可以读取这些数据。
给出了写过程的代码:
public boolean writeToFile(String dataLine) {
dataLine = "\n" + dataLine;
try {
File outFile = new File(filepath);
dos = new DataOutputStream(new FileOutputStream(outFile));
dos.writeBytes(dataLine);
dos.close();
} catch (FileNotFoundException ex) {
return (false);
} catch (IOException ex) {
return (false);
}
return (true);
}
任何人都可以根据需要对代码进行更改并将其发布给我。
[FileOutputStream的Java API] [1]指出:
public FileOutputStream(String name,
boolean append)
throws FileNotFoundException)
创建输出文件流以写入具有指定名称的文件。 如果第二个参数为true,则字节将被写入文件的末尾而不是开头。 创建一个新的FileDescriptor对象来表示此文件连接。
因此,您的代码应如下所示:
public boolean writeToFile(String dataLine) {
dataLine = "\n" + dataLine;
try {
File outFile = new File(filepath);
dos = new DataOutputStream(new FileOutputStream(outFile,true));
dos.writeBytes(dataLine);
dos.close();
} catch (FileNotFoundException ex) {
return (false);
} catch (IOException ex) {
return (false);
}
return (true);
}
[1]: http : //download.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.lang.String ,boolean)
将构造函数FileOutputStream(File file, boolean append)
与append = true一起使用
参见[http://download.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File,boolean)] [1]
另请注意,您可能应该使用FileWriter编写文本。 FileOutputStream用于二进制数据。
[1]: http : //download.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File ,boolean)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.