views:

83

answers:

4

Hey guys,

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!

+3  A: 

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: http://stackoverflow.com/questions/2714385/read-text-file-in-java

Tansir1
That's exactly what I needed. Thanks!
Jeff
+1  A: 

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();
}
Stephen C
+2  A: 

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

Gopi
Scanner? Isn't that a little old?
TheLQ
@Lord Quackstar: `Scanner` was introduced in java 1.5. Using `BufferedReader` for these purpose is old.
tulskiy
A: 

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);
}
mwooten.dev
That sounds like overkill when it comes to a BufferedFileReader.
monksy