這個範例程式碼是來自Java Tips,ㄚ琪覺得好用就拿來這邊獻醜翻譯了,如果有涉及翻譯侵權的話,尚請告知。
這個範例程式碼會讀取MyFile.txt,然後在主控台印出內容,它會以DataInputStream的格式一行行地讀取。
import java.io.BufferedInputStream;import java.io.DataInputStream;import java.io.File;
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * This program reads a text file line by line and print to the console. It uses * FileOutputStream to read the file. * */ public class FileInput { public static void main(String[] args) { File file = new File(“C:MyFile.txt”); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); // Here BufferedInputStream is added for fast reading. bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); // dis.available() returns 0 if the file does not have more lines. while (dis.available() != 0) { // this statement reads the line from the file and print it to // the console. System.out.println(dis.readLine()); } // dispose all the resources after using them. fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
請閱讀深入淺出 Java 程式設計 第二版的第十四章《保存物件》有詳細簡單的說明,自學無效請參考上學習,功力夠了可點下面推廣連結上1111填履歷找Java類工作。
下個步驟繼續參閱之前的如何用Java讀取XML檔案學習。