导入Textfile并在Java中逐行读取

我想知道如何导入文本文件。 我想导入一个文件,然后逐行读取。

谢谢!

我不知道“导入”文件是什么意思,但这是使用标准Java类逐行打开和读取文本文件的最简单方法。 (这应该适用于所有版本的Java SE回JDK1.1。使用Scanner是JDK1.5及更高版本的另一个选项。)

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

这应该涵盖您需要的一切。

http://download.oracle.com/javase/tutorial/essential/io/index.html

对于一个具体的例子: http : //www.java-tips.org/java-se-tips/java.io/how-to-read-file-in-java.html

这也可能有所帮助: 用Java读取文本文件

我没有得到’import’的意思。 我假设您要读取文件的内容。 这是一个执行它的示例方法

  /** 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); } 

有关详细信息,请参阅此处

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); }