先作一個txt檔, 名稱是SampleFile.txt.
內容是Java Tiger
Ex_FileInputStream
import java.io.*;
import static java.lang.System.out;
public class Ex_FileInputStream{
public static void main(String args[]){
byte[] buffer;
int totalBytes;
FileInputStream fis = null;
try{
fis = new FileInputStream("SampleFile.txt");
totalBytes = fis.available(); //呼叫 .available()來得到資料為元組總數量是多少Bytes.
System.out.println("Can Read Byte: "+totalBytes+" bytes");
buffer = new byte[1]; //設緩衝區大小, 讓read可以將資料讀入此處
out.println("Data:");
out.println("------------------------");
while(fis.read(buffer)!=-1){
out.print("("+(char)buffer[0]+")");
}
}catch(IOException e){
}finally{
try{
fis.close();
}catch(IOException e){
}
}
}
}
------------------------------------------------------------------------------------------------------------
Can Read Byte: 13 bytes <- 檔案內容Byte數量
Data:
------------------------
(?)(?)(?)(J)(a)(v)(a)( )(T)(i)(g)(e)(r) <- 我用()來把內容分隔出來
------------------------------------------------------------------------------------------------------------
問題:
照理說資料內容的Byte數量應該是10.
但是現在卻是13, 就是多了前面的???,
用整數顯示
(-17)(-69)(-65)(74)(97)(118)(97)(32)(84)(105)(103)(101)(114)
Ex_FileInputStream_3
import java.io.*;
public class Ex_FileInputStream_3{
public static void main(String args[]){
byte[] buffer;
int totalBytes;
FileInputStream fis = null;
try{
fis = new FileInputStream("SampleFile.txt");
totalBytes = fis.available();
System.out.println("Can Read Byte: " + totalBytes +" Bytes.\n");
buffer = new byte[totalBytes];
if(fis.read(buffer) == totalBytes){
int i = 0;
System.out.println("Data: ");
System.out.println(" -*---------------- ");
String s = new String(buffer);
System.out.println(" (" +s+")");
}else{
System.out.println("Error");
}
}catch(IOException e){
}finally{
try{
fis.close();
}catch(IOException e){
}
}
}
}
試用整串字串輸入,
= =
但是還是不行..
WWWWWHHHHHYYYYYY
沒有留言:
張貼留言