Java按行读写文件

public class FileUtil {
	// 判断指定文件是否存在,若isCreate=true则文件不存在时创建
	public static boolean exist(String filename, boolean isCreate) throws IOException {
		File file = new File(filename);
		boolean exist = file.exists();
		if(exist) return true; // 文件存在返回true
		if(isCreate) return file.createNewFile(); // 文件不存在且需要创建时返回是否创建成功
		return false; // 文件不存在且不需要创建时返回false
	}
	
	// 写入文件,append=true为追加方式写入
	public static void writeFile(String fileName,String str, boolean append) throws IOException{                
            FileWriter fw = new FileWriter(fileName, append);
            fw.write(str);
            fw.flush();
            fw.close();
        } 
	
	// 按行写入文件,append=true为追加方式写入
	public static void writeFileByLines(String fileName,String []strs, boolean append) throws IOException{                
            FileWriter fw = new FileWriter(fileName, append);
            for (String str: strs){
                fw.write(str);
                fw.write("\n");
            }        
            fw.flush();
            fw.close();
        } 
	
	// 按行读取文件
    public static List<String> readFileByLines(String fileName) throws IOException{
        File file = new File(fileName);
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String tempString = null;
        List<String> strs = new ArrayList<String>();
        while ((tempString = reader.readLine()) != null){
            strs.add(tempString);
        }
        reader.close();
        return strs;
    }  
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值