首页 > 代码库 > java 按行读写文件

java 按行读写文件

         因为经常会在写小程序中用到java 的 按行读写文件,所以在这就把模板站出来。

package com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class Main {

	private static ArrayList<String> list = null;
	//获取对应操作系统的换行符
	private final static String EOL = System.getProperty("line.separator");
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		//模拟copy操作
		String file_name = "";
		readForLine(file_name);
		writeForLine(file_name + ".bak");
		
	}
	
	//按行读取文件file_name,并把每一行的数据存储在list中
	public static void readForLine(String file_name)
	{
		File file = new File(file_name);
		BufferedReader reader = null;
		
		try {
			reader = new BufferedReader(new FileReader(file));
			String line = null;
			//按行读,并把每次读取的结果保存在line字符串中
			while ( (line = reader.readLine()) != null )
			{
				list.add(line);
				System.out.println(line);
			}
			//关闭流
			reader.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
		{
			//当由于异常情况,上面关闭流程序没有执行时
			if ( reader != null )
			{
				try
				{
					reader.close();
				}catch(IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}
	
	//按行写文件,将list中的字符串,按行写入file_name文件中
	public static void writeForLine(String file_name)
	{
		File file = new File(file_name);
		BufferedWriter writer = null;
		
		try {
			writer = new BufferedWriter(new FileWriter(file));
			for ( String elem: list )
			{
				writer.write(elem + EOL);//按行写文件,后面追加行分隔符EOL
			}
			//关闭流
			writer.close();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
		{
			if ( writer != null )
			{
				try {
					writer.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}


java 按行读写文件