天天看點

Java--字元流和位元組流

IO流分類:

  • 流向:

    輸入流:讀資料 FileReader

    輸出流:寫資料 FileWriter

  • 資料類型
    位元組流:
     		位元組輸入流     讀取資料     FileInputStream
     		位元組輸出流     寫出資料     FileOutputStream
     
     字元流
     		字元輸入流     讀取資料     Reader
     		字元輸出流     寫出資料    Writer
               

複制圖檔

package com.it03;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/*
 * 	使用字元流和位元組流複制圖檔
 * 	
 * 	二進制檔案隻能使用位元組流進行複制
 * 	文本檔案的複制既能使用字元流也能使用位元組流
 * 		
 */
public class IOClassDemo {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		//無法進行圖檔的複制
		//function();
		
		//建立位元組輸入流對象
		FileInputStream fis = new FileInputStream("a.jpg");
		//建立位元組輸出流對象
		FileOutputStream fos = new FileOutputStream("b\\a.jpg");
		
		//進行資料的讀取和複制,一次讀取一個位元組數組的方式
		int len;
		byte[] bys = new byte[1024];
		while((len=fis.read(bys))!=-1) {
			fos.write(bys,0,len);
			
		}
		
		//釋放資源
		fis.close();
		fos.close();
		

	}

	private static void function() throws FileNotFoundException, IOException {
		//建立字元輸入流對象
		FileReader fr = new FileReader("a.jpg");
		//建立字元輸出流對象
		FileWriter fw = new FileWriter("b\\a.jpg");
		
		//一次讀寫一個字元數組
		int len;//用于存儲讀到的字元個數
		char[] chs = new char[1024];
		while((len=fr.read(chs))!=-1) {
			fw.write(chs,0,len);
			fw.flush();
			
		}
		//釋放資源
		fw.close();
		fr.close();
	}

}

           

使用位元組流複制文本檔案

package com.it03;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 	使用位元組流複制文本檔案
 * 	
 */
public class IOClassDemo2 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		//建立位元組輸入流對象
		//File f = new File("src\\com\\it03\\IOClass.java");
		FileInputStream fis = new FileInputStream("src\\com\\it03\\IOClass.java");
		//建立位元組輸出流對象
		FileOutputStream fos = new FileOutputStream("b\\IOC.java");
		
		
		//文本的複制
		//一次讀寫一個位元組
		int by;
		while((by=fis.read())!=-1) {
			fos.write(by);
		}
		
		//一次讀寫一個位元組數組
		int len;
		byte[] bys = new byte[1024];
		while((len=fis.read(bys))!=-1) {
			fos.write(bys,0,len);
			
		}
		
		
		
		//釋放資源
		fis.close();
		fos.close();
				
	}

}