1. 程式人生 > 其它 >第一部分 位元組輸出流

第一部分 位元組輸出流

//1.編碼: 把文字轉換成字元(使用指定的編碼)
String name = "abc我愛你中國";
//byte[] bytes = name.getBytes();//以當前程式碼預設字符集進行編碼(UTF-8) 3+5*3
byte[] bytes = name.getBytes("GBK");//指定編碼
System.out.println(bytes.length);
System.out.println(Arrays.toString(bytes));

//2.解碼: 把字元轉換成對應的中文形式(編碼前 和 編碼後的字符集必須一致, 否則亂碼)
//String rs = new String(bytes);//預設UTF-8
String rs = new String(bytes,"GBK");//指定GBK解碼
System.out.println(rs);




//1. 建立一個檔案位元組輸入流管道與原始檔接通
//InputStream is = new FileInputStream(new File("io_project\\src\\data.txt"));
InputStream is = new FileInputStream("E:\\idea_java_project\\io_project\\src\\data.txt");

// //2. 讀取一個位元組返回 (每次讀取一滴水)
// int b1 = is.read();
// System.out.println((char)b1);
//
// int b2 = is.read();
// System.out.println((char)b2);
//
// int b3 = is.read();
// System.out.println(b3);//讀取完畢,返回-1

//3.使用迴圈改進
//定義一個變數記錄每次讀取的字元
int b;
while((b = is.read()) != -1){
System.out.print((char)b);
}
---------------------------------------------


目標: 使用檔案位元組輸入流 每次讀取一個位元組陣列的資料

public class FileInputDemo02 {
public static void main(String[] args) throws Exception{
//1.建立一個位元組輸入流管道與原始檔接通
InputStream is = new FileInputStream("E:\\idea_java_project\\io_project\\src\\data.txt");

//2.要定義一個位元組陣列,用於讀取位元組陣列
byte[] buffer = new byte[3];
int len = is.read(buffer);
System.out.println("讀取了幾個位元組:"+len);
String rs = new String(buffer);
System.out.println(rs);

int len1 = is.read(buffer);
System.out.println("讀取了幾個位元組:"+len1);
String rs1 = new String(buffer);
System.out.println(rs1);

int len2 = is.read(buffer);
System.out.println("讀取了幾個位元組:"+len2);
String rs2 = new String(buffer,0,len2);
System.out.println(rs2);

//3. 改進使用迴圈, 每次讀取一個位元組陣列
byte[] buffer = new byte[3];
int len ;//記錄每次讀取的位元組數
while((len = is.read(buffer)) != -1){
//讀取多少倒出多少
System.out.print(new String(buffer,0,len));
}

}
}
---------------------------
  1. 如何使用位元組輸入流讀取中文內容輸出不亂嗎呢?

    定義一個與檔案一樣大的位元組陣列, 一次性讀取完檔案的全部位元組

 

  1. 直接把檔案陣列全部讀取到一個位元組陣列可以避免練嗎, 是否存在問題?

    如果檔案過大, 位元組陣列可能引起記憶體溢位.

//1.建立一個位元組輸入流管道與原始檔接通
File f = new File("E:\\idea_java_project\\io_project\\src\\data.txt");
InputStream is = new FileInputStream(f);

//2.定義一個位元組陣列與檔案的大小剛剛一樣大
byte[] buffer = new byte[(int)f.length()];
int len = is.read(buffer);
System.out.println("讀取了多少位元組"+len);
System.out.println("檔案大小"+f.length());
System.out.println(new String(buffer));