import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** 一、讀取文件 1、建立聯系 File對象 源頭 2、選擇流 文件輸入流 InputStream FileInputStream 3、操作 : byte[] car =new byte[1024]; +read+讀取大小 --->輸出 4、釋放資源 :關閉 */ public class ReadFile { public static void main(String[] args) { String string = "F:/read.txt"; myRead(string); } /** * 讀取文件 * @param string */ public static void myRead(String string){ File file = new File(string); //1、建立連接 InputStream is = null; try { is = new FileInputStream(file); //2、選擇流(此處為輸入流) // //和上一句功能一樣,BufferedInputStream是增強流,加上之后能提高輸入效率,建議! // is = new BufferedInputStream(new FileInputStream(file)); int len = 0; byte[] car = new byte[1024]; while((len = is.read(car))!= -1) { //3、操作:以每次car大小讀取 String ss = new String(car,0,len); // 將byte類型的數組轉化成字符串,方便下面輸出 System.out.println(ss); } } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("文件不存在!"); } catch (IOException e) { e.printStackTrace(); System.out.println("讀取文件失敗!"); }finally { if (is != null) { //若is還存在就需要釋放,否則不需要釋放 try { is.close(); } catch (IOException e) { e.printStackTrace(); System.out.println("關閉文件輸入流失敗"); } } } } }