1. 程式人生 > 其它 >Java筆記 位元組輸入流讀取檔案中的字元

Java筆記 位元組輸入流讀取檔案中的字元

1.構造輸入流,讀取一個位元組

read();從輸入流中讀取資料的下一個位元組,返回的是一個int型別的值

 

public void testFileInputStream() {
FileInputStream input =null;
try {
input = new FileInputStream("Test/demo02.txt");
int a = input.read();
System.out.println((char)a);
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(input!=null)
input.close();//關閉輸入流,釋放資源
} catch (IOException e) {
e.printStackTrace();
}
}
}

 

2.使用輸入流迴圈讀取檔案中所有字元

(1)一個位元組一個位元組讀取

 

public void testFileInputStream() {
FileInputStream input =null;
try {
input = new FileInputStream("Test/demo02.txt");
int a =-1;
while( (a = input.read())>-1 ) {//read()方法讀取到檔案末尾會返回-1
System.out.print((char)a);//將int型別強制轉換為char型別
}//中文不止佔有一個位元組
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(input!=null)
input.close();//關閉輸入流,釋放資源
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

 

(2)按位元組陣列讀取read(byte[] b);

法一

public void testFileInputStream() {
FileInputStream input =null;
try {
input = new FileInputStream("Test/demo02.txt");
byte[] data = new byte[4];
int length = -1;
while( (length = input.read(data))>-1 ) {

for(int i=0;i<length;i++) {
System.out.print((char)data[i]);
}
}
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(input!=null)
input.close();//關閉輸入流,釋放資源
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

法二

public void testFileInputStream() {
FileInputStream input =null;
try {
input = new FileInputStream("Test/demo02.txt");
byte[] data = new byte[4];
int length = -1;
while( (length = input.read(data))>-1 ) {
String str = new String(data,0,length);
System.out.print(str);
}
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(input!=null)
input.close();//關閉輸入流,釋放資源
} catch (IOException e) {
e.printStackTrace();
}
}
}
}