Import a text file and read line by line in Java

I was wondering how one could import a text file. I want to import a file and then read it one by one.

thank!

+3
source share
4 answers

I have no idea what you mean by โ€œimportingโ€ a file, but here is the easiest way to open and read a text file line by line using only standard Java classes. (This should work for all versions of Java SE in 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();
}
+11
source

, . , . ,

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

.

+4

Apache Commons IO LineIterator, . FileUtils : FileUtils.lineIterator().

:

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

Source: https://habr.com/ru/post/1758579/


All Articles