Java IO 输入输出流 实例解释

package IO;
/*
 * Java In Out 输入输出流
 * Date:2014.02.21
 * Author:璀若星辰
 *reference
 * */
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;


/*主要操作的内容:
 * 1.字节流: 图片,     2.字符流  (字符文件 .html .java .txt)
 *
 *
 * */
public class testIO {
	//读 字符输入流
	public static ListtestCharInput() throws Exception {
		FileInputStream fis = new FileInputStream("D:/1.txt");
		try {
			InputStreamReader isr = new InputStreamReader(fis, "gb2312");
			try{
				BufferedReader br = new BufferedReader(isr);
				try{
					List all = new ArrayList();
					String temp = br.readLine();
					while(temp!=null) {
						System.out.println("temp="+temp);
						all.add(temp);
						System.out.println("all= "+all);
						temp= br.readLine();
					}
					return all;
				}finally{
					br.close();
				}
			}finally{
				isr.close();
			}
		} finally{
			fis.close();
		}

	}
	 // 读 字节流
	 public static void testByteInputStream() throws Exception {
		    FileInputStream fis = new FileInputStream("D:/1.txt");
		    try {
		      BufferedInputStream bis = new BufferedInputStream(fis);
		      try {
		        byte[] bs = new byte[1024];  //1024的长度可改
		        while (bis.read(bs, 0, 1024) != -1) {
		          System.out.print("bs="+new String(bs));
		        }
		      } finally {
		        bis.close();
		      }
		    } finally {
		      fis.close();
		    }

		  }
	 //写 字符流
	 public static void testCharOutput(Listlist) throws Exception{
		 FileOutputStream fos = new FileOutputStream("d:/1.txt");
		 try{
			 OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");//文件的编码
			 try{
				 BufferedWriter bw = new BufferedWriter(osw);
				 try{
					 for(String line:list){
						 bw.write(line);
						 bw.newLine();//使用newLine()换行  \n
					 }
					 System.out.println("success");
				 }finally{
					 bw.close();
				 }
			 }finally{
				 osw.close();
			 }
		 }finally{
			 fos.close();
		 }
	 }
	public static void main(String[] args) throws Exception {
		//testIO.testCharInput();
		//testIO.testByteInputStream();
		ArrayList list = new ArrayList();
		list.add("Happy");
		list.add("Boy");
		testIO.testCharOutput(list);
		testIO.testByteInputStream();
	}
	//写入内容时不想删除原来的文本,可以先读出来保存下来,然后和新内容一起写入文本,此处不再赘述
}

你可能感兴趣的:(java)