天天看点

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("读取结束");
		
	}
}