java写入文件的几种方法(一)

1. FileWritter写入文件

FileWritter, 字符流写入字符到文件。默认情况下,它会使用新的内容取代所有现有的内容,如下:

new FileWriter(file);

然而,当指定一个true (Boolean)值作为FileWritter构造函数的第二个参数,它会保留现有的内容,并追加新内容在文件的末尾,如下:

new FileWriter(file,true);

举个例子:

一个文件名为test_appendfile.txt,包含以下内容:Hello World,需要追新内容,代码如下:

package com.andy.file;



import java.io.File;

import java.io.FileWriter;

import java.io.BufferedWriter;

import java.io.IOException;

public class AppendToFileTest

{

public static void main( String[] args )

{

    try{
 
        String content = "A cat will append to the end of the file";
 
        File file =new File("test_appendfile.txt");
 
        if(!file.exists()){
        	file.createNewFile();
        }
 
        //使用true,即进行append file 
 
        FileWriter fileWritter = new FileWriter(file.getName(),true);
 
 
        fileWritter.write(content);
 
        fileWritter.close();
 
        System.out.println("finish");
 
    }catch(IOException e){
 
        e.printStackTrace();
 
    }

}

}

执行结果:

可打开文本文件“test_appendfile.txt”,内容更新如下:

Hello world A cat will append to the end of the file

2.BufferedWriter写入文件

缓冲字符(BufferedWriter )是一个字符流类来处理字符数据, 但又不同于字节流(数据转换成字节),你可以直接写字符串,数组或字符数据保存到文件。

package com.andy.file;


import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

public class WriteToFileTest2 {

	public static void main(String[] args) {
		
		try {
				String content = "a dog will be write in file";
				File file = new File("test_appendfile2.txt");
				if(!file.exists()){
					file.createNewFile();
				}
				FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
				BufferedWriter bw = new BufferedWriter(fileWriter);
				bw.write(content);
				bw.close();
				System.out.println("finish");
		    } catch (IOException e) {
		        e.printStackTrace();
		    }
	}

}

执行完后,打开test_appendfile2.txt文件即可看到。

  • 29
    点赞
  • 111
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值