1. 程式人生 > >java 利用輸入輸出流處理txt檔案,並生成新txt檔案

java 利用輸入輸出流處理txt檔案,並生成新txt檔案

直接上程式碼:

import java.io.*;
import java.util.Calendar;

public class TestTxt {
	@org.junit.Test
	public void test2(){
		long starttime=System.currentTimeMillis();
		try {
			File file1=new File("d:\\test.txt");//讀取檔案
			FileReader fr =new FileReader(file1);
			File file2=new File("d:\\newFile.txt");//新生檔案
			if(file2.exists()){ //如果新生檔案存在,新生檔案重新命名
				String pathname="D:\\newFile"+getTimeByCalendar()+".txt";
				file2=new File(pathname);
			}
			FileWriter fw =new FileWriter(file2);

			BufferedReader br=new BufferedReader(fr);
			BufferedWriter bw=new BufferedWriter(fw);

			String temp=null;
			long time222=System.currentTimeMillis();
			System.out.println("中耗時:"+(time222-starttime)+"ms");
			while((temp=br.readLine())!=null){ //讀取行資料
				String[] str=temp.split("\\s+");
				long ip1=ipToLong(str[0]);
				long ip2=ipToLong(str[1]);
				StringBuilder newStr=new StringBuilder();
				newStr.append(ip1);
				newStr.append(" ");
				newStr.append(ip2);
				newStr.append(" ");
				for (int i=0;i<str.length;i++){
					if(i!=5){
						newStr.append(str[i]);
						newStr.append(" ");
					}
				}
					bw.write(newStr.toString()); //向新生的檔案寫入行資料
					bw.newLine();//換行
			}
			long time333=System.currentTimeMillis();
			System.out.println("迴圈耗時:"+(time333-time222)+"ms");
			bw.flush();
			br.close();
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		long endtime=System.currentTimeMillis();
		System.out.println("總耗時:"+(endtime-starttime)+"ms");
	}

	public String getTimeByCalendar(){
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);//獲取年份
		int month=cal.get(Calendar.MONTH);//獲取月份
		int day=cal.get(Calendar.DATE);//獲取日
		int hour=cal.get(Calendar.HOUR);//小時
		int minute=cal.get(Calendar.MINUTE);//分
		int second=cal.get(Calendar.SECOND);//秒
		int WeekOfYear = cal.get(Calendar.DAY_OF_WEEK);//一週的第幾天
		System.out.println("現在的時間是:公元"+year+"年"+month+"月"+day+"日"+hour+"時"+minute+"分"+second+"秒       星期"+WeekOfYear);
		String time=year+""+month+""+day+""+hour+""+minute+""+second;
		return time;
	}
	/**
	 * 將ip轉成數字
	 *
	 */
	public static long ipToLong(String strIP) {
		long[] ip = new long[4];
		String[] ipSec = strIP.split("\\.");
		for (int k = 0; k < 4; k++) {
			ip[k] = Long.valueOf(ipSec[k]);
		}
		return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
	}

}

檔案處理前:

處理後: