2010-08-08 116 views

回答

10

我不知道你所說的「導入」文件的意思,但在這裏是最簡單的方法使用標準的Java類來逐行打開和讀取文本文件。 (這應該對Java SE的所有版本回到JDK1.1,使用掃描儀是JDK1.5另一種選擇和更高版本。)

BufferedReader br = new BufferedReader(
     new InputStreamReader(new FileInputStream(fileName))); 
try { 
    String line; 
    while ((line = br.readLine()) != null) { 
     // process line 
    } 
} finally { 
    br.close(); 
} 
4

我沒有得到你說「進口」是什麼意思。我假設你想要讀取文件的內容。下面是做它

/** Read the contents of the given file. */ 
    void read() throws IOException { 
    System.out.println("Reading from file."); 
    StringBuilder text = new StringBuilder(); 
    String NL = System.getProperty("line.separator"); 
    Scanner scanner = new Scanner(new File(fFileName), fEncoding); 
    try { 
     while (scanner.hasNextLine()){ 
     text.append(scanner.nextLine() + NL); 
     } 
    } 
    finally{ 
     scanner.close(); 
    } 
    System.out.println("Text read in: " + text); 
    } 

詳細的實例方法,你可以看到here

+1

掃描儀?這不是有點老嗎? – TheLQ 2010-08-08 04:46:36

+3

@ Quackstar:'掃描儀'是在java 1.5中引入的。爲此目的使用'BufferedReader'是舊的。 – 2010-08-08 04:59:28

0

Apache Commons IO提供了一個稱爲LineIterator偉大的實用工具,可明確用於此目的。 FileUtils類有一個爲文件創建一個的方法:FileUtils.lineIterator(File)。

下面是使用它的一個例子:

File file = new File("thing.txt"); 
LineIterator lineIterator = null; 

try 
{ 
    lineIterator = FileUtils.lineIterator(file); 
    while(lineIterator.hasNext()) 
    { 
     String line = lineIterator.next(); 
     // Process line 
    } 
} 
catch (IOException e) 
{ 
    // Handle exception 
} 
finally 
{ 
    LineIterator.closeQuietly(lineIterator); 
} 
+0

這對於BufferedFileReader來說聽起來像是過度殺毒。 – monksy 2010-08-08 05:24:42