1. 程式人生 > >[5.23]Java 基礎知識 (IO流)

[5.23]Java 基礎知識 (IO流)

什麼是IO流

流(Stream):源於UNIX中管道(pipe)的概念。在UNIX中,管道是一條不間斷的位元組流,用來實現程式或程序間的通訊,或讀寫外圍裝置,外部檔案等。

IO流分為幾類

兩類:位元組流和字元流

什麼是位元組流?什麼是字元流?

位元組流的概念:位元組流是由位元組組成的,位元組流是最基本的,所有的InputStream和OutputStream的子類都是位元組流,主要用在處理二進位制資料,它是按位元組來處理的。

字元流的概念:字元流是由字元組成的,Java裡字元由兩個位元組組成,所有的Reader和Writer的子類都是字元流,主要用在處理文字內容特定字元


位元組流和字元流的區別

位元組流操作的基本單元為位元組;字元流操作的基本單元為Unicode碼元。

位元組流預設不使用緩衝區;字元流使用緩衝區。

位元組流通常用於處理二進位制資料,實際上它可以處理任意型別的資料,但它不支援直接寫入或讀取Unicode碼元;字元流通常處理文字資料,它支援寫入及讀取Unicode碼元。

字元流的常用類有哪些

Reader:BufferedReader;

               InputStreamReader;

               FileReader;

Write:BufferedWriter;

             OutputStreamWriter;

             FileWriter;

實現檔案複製的思路和步驟是什麼

public class Ex3 {
	public static void main(String[] args) {
		FileInputStream input = null;
		FileOutputStream  output = null;
		int n = 0;
		try {
		
			input = new FileInputStream("D:\\Lenovo\\info.txt");
			output = new FileOutputStream("D:\\Lenovo\\info1.txt");
	
			do {
				n = input.read();
				output.write(n);
			}while (n!=-1);
			
		}catch (FileNotFoundException e){
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				input.close();
				output.close();
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

如何使用字元流進行檔案讀寫

public class Test {
	public static void main(String[] args) {
		int count = 0;
		FileReader reader = null;
		BufferedReader breader =null;
		BufferedWriter writer = null;
		try {
			reader = new FileReader("D:\\Lenovo\\inof.txt");
			writer = new BufferedWriter(new FileWriter("D:\\Lenovo\\info.txt"));
			breader = new BufferedReader(reader);
			String temp ="";
			while((temp=breader.readLine())!=null){
				writer.write(temp);
				writer.newLine();
			}
			writer.flush();
			System.out.println("共迴圈"+count+"次");	
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				try {
					breader.close();
					reader.close();
					writer.close();
				}catch (IOException e) {
					e.printStackTrace();
				}
		
			
		
		}
	}

}