2010-08-08 117 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