Java将字符串保存到文件中

本文提供了两种使用Java进行文件写入的方法示例:一种是通过FileOutputStream直接写入字节;另一种是利用FileWriter结合BufferedWriter追加写入文本。这两种方法适用于不同的应用场景。

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

public void WriteToFile1() throws Exception {
		String str = "xinxi";
		File file = new File("file\\userConfig.xml");
		FileOutputStream fos = null;
		if (!file.exists()) {
			file.createNewFile();
		}
		fos = new FileOutputStream(file);
		byte bytes[] = new byte[1024];
		bytes = str.getBytes();
		int b = str.length();
		fos.write(bytes, 0, b);
		fos.close();
	}

	public void WriteToFile2() throws Exception {
		String str = "xinxi";
		FileWriter fw = new FileWriter("userConfig.xml", true);
		BufferedWriter bw = new BufferedWriter(fw);
		bw.newLine();
		bw.write(str);
		bw.close();
		fw.close();

	}

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值