public class TextFileAppendDataTest {
static void readTxtFile(InputStreamReader reader) throws IOException {
if (reader == null) {
return;
}
char[] buff = new char[1024];
while (reader.read(buff) != -1) {
System.out.println(String.valueOf(buff));
}
}
static void writeTxtFile(OutputStreamWriter writer) throws IOException {
if (writer == null) {
return;
}
//FileWriter k=new FileWriter("",true);
// writer.append(csq, start, end) // append方法是骗人的,实际上就是清空当前的文本信息,最后在写入数据
String writeContext = "\r\n你好这是追加数据内容!";
writer.write(writeContext);
// writer.appedn("\r\n你好这是追加数据内容!"); // 错误
writer.flush();
}
public static void main(String[] args) {
// 1. 追加文本数据前
String txtFilePath = "tmp/txtFile.txt";
File file = new File(txtFilePath);
if (!file.exists()) {
System.out.println("当前需要追加数据的文件不存在");
return;
}
// 显示追加前的文本信息
// 直接使用try()方式,由于当前的流只要实现了Closeable就可以自动关闭流了
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fis)) {
System.out.println("写入数据前文本信息!");
readTxtFile(reader);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 向文本文件中追加数据
// FileOutputStream fos = new FileOutputStream(file,true);//加了true就是追加数据(无论是write或者appedn都是追加数据)
// FileOutputStream fos = new FileOutputStream(file); // 默认就是清空数据,然后写入(无论调用write或者append都是一样)
try (FileOutputStream fos = new FileOutputStream(file,true);
OutputStreamWriter writer = new OutputStreamWriter(fos)) {
writeTxtFile(writer);
System.out.println("写入数据成功!");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("更新后的文本信息为:");
// 显示追加后的文本信息
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fis)) {
readTxtFile(reader);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Java 操作文本文件追加数据,在文件不存在的情况下创建
最新推荐文章于 2022-10-10 11:42:47 发布