Import Textfile and read line by line in Java

2019-05-10 00:06发布

问题:

I was wondering how one would go about importing a text file. I want to import a file and then read it line by line.

thanks!

回答1:

I've no idea what you mean by "importing" a file, but here's the simplest way to open and read a text file line by line, using just standard Java classes. (This should work for all versions of Java SE back to JDK1.1. Using Scanner is another option for JDK1.5 and later.)

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


回答2:

This should cover just about everything you need.

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

And for a specific example: http://www.java-tips.org/java-se-tips/java.io/how-to-read-file-in-java.html

This might also help: Read text file in Java



回答3:

I didnt get what you meant by 'import'. I assume you want to read contents of a file. Here is an example method that does it

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

For details you can see here



回答4:

Apache Commons IO offers a great utility called LineIterator that can be used explicitly for this purpose. The class FileUtils has a method for creating one for a file: FileUtils.lineIterator(File).

Here's an example of its use:

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