Java 操作文本文件追加数据,在文件不存在的情况下创建

本文介绍了如何在Java中使用`FileInputStream`和`OutputStreamWriter`进行文本文件的读取和追加操作,重点讲解了`readTxtFile`和`writeTxtFile`方法,并处理了可能出现的IOException。通过实例展示了如何确保数据正确追加到文件中,包括检查文件是否存在和正确关闭流。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
		}

	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值