import java.io.File; import java.io.FileInputStream; public class FileTest { public static void main(String[] args) { FileInputStream fis = null; try { File file = new File("D://test.txt"); fis = new FileInputStream(file); byte[] b = new byte[(int)file.length()]; while (fis.read(b) != -1) { } System.out.println(new String(b)); } catch (Exception e) { e.printStackTrace(); } } }
或者
//用哪個 bufferedReader 讀。 FileReader fr =new FileReader("...txt"); BufferedReader br=new BufferedReader(fr); StringBuffer sb = new StringBuffer(); String str = null; while ((str = br.readLine()) != null) sb.append(str);
兩個都屬於字節流讀取方式。
char 的范圍是0~255
byte 的范圍是-128~127
用char型就能讀出該數據的ASCII字符,
如果用byte讀出來就將是數字,並且有可能是負數。
而你這個例子,無疑是想打印出該文件中,各個字節的ASCII碼。所以轉成了char型,再把char轉成int型。
一般純文本文件,我們都可以用char來讀取。
但對於非文本文件,我們就最好用byte來讀了,因為我們讀到的那個字節很可能不是正數。
FileInputStream file=new FileInputStream("filename"); InputStreamReader isr=new InputStreamReader(file); BufferedReader br=new BufferedReader(isr); try{ String show=br.read()Line(); while(show!=null){ //String show=br.read()Line(); System.out.println(show); show=br.readLine(); } }