天天看點

IO 讀取檔案、寫出到檔案的普通方法

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import org.junit.Test;

public class IODemo {
	
	@Test
	public void Output(){
		File file = new File("D:"+File.separator+"a"+File.separator+"output.dat");
		
		/*處理檔案與目錄*/
		if(!file.exists()){
			//建立目錄
			File dir = file.getParentFile();
			if(!dir.exists()){
				dir.mkdirs();	
			}
			
			//建立新檔案
			try {
				file.createNewFile();
			} catch (IOException e) {
				System.out.println("建立新檔案失敗");
			}
			
		}
		
		PrintWriter pw = null;
		try {
			//位元組輸出流,在原檔案後追加
			FileOutputStream fos = new FileOutputStream(file,true);
			
			//設定字元集
			OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
		
			//緩沖字元輸出流
			pw = new PrintWriter(osw);

			pw.println("呵呵!");
			pw.println("哈哈");
			pw.println("摩擦");
			
			pw.append("摩擦");
			pw.append("摩擦");
			pw.append("魔鬼的步伐");
		} catch (FileNotFoundException e) {
			System.out.println("指定的File沒找到!");
		} catch (UnsupportedEncodingException e) {
			System.out.println("系統不支援的編碼!");
		} finally{
			if(pw != null){
				pw.close();
			}
		}
		
		
		System.out.println("輸出結束");
		
	}
	
	@Test
	public void Input(){
		File file = new File("D:"+File.separator+"a"+File.separator+"output.dat");
		
		/*處理檔案與目錄*/
		if(!file.exists()){
			throw new IllegalArgumentException("目錄:"+file+"不存在.");
		}
		
		
		BufferedReader br = null;
		try {
			//位元組輸出流,在原檔案後追加
			FileInputStream fis = new FileInputStream(file);
			
			//設定字元集
			InputStreamReader isw = new InputStreamReader(fis,"utf-8");
		
			//緩沖字元輸出流
			br = new BufferedReader(isw);

			StringBuffer sb = new StringBuffer();
			String read = null;
			while((read=br.readLine()) != null){
				sb.append(read+"\n");
			}
			System.out.println(sb);
			
		} catch (FileNotFoundException e) {
			System.out.println("指定的File沒找到!");
		} catch (UnsupportedEncodingException e) {
			System.out.println("系統不支援的編碼!");
		} catch (IOException e) {
			System.out.println("不知道是什麼錯誤");
		}finally{
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					System.out.println("輸入流關閉異常");
				}
			}
		}
		
		
		System.out.println("讀取結束");
		
	}
}