Java read from file line by line

How to read text file line by line in Java

In Java File I/O programming, the classes BufferedReader and LineNumberReader allows reading a sequence of lines from a text file, in a line-by-line fashion, by using their readLine() method. The LineNumberReader is a subclass of the BufferedReader class. The only difference is that, the LineNumberReader class keeps track of the current line number, whereas the BufferedReader class does not.

Reading all lines from a text file using the BufferedReader class is as easy as follows:

String filePath = «Path/To/Your/Text/File.txt»; try < BufferedReader lineReader = new BufferedReader(new FileReader(filePath)); String lineText = null; while ((lineText = lineReader.readLine()) != null) < System.out.println(lineText); >lineReader.close(); > catch (IOException ex)

The above code snippet takes a given text file, reads every line and prints content of each line to the console output. It’s also common to read and put all the lines into a collection (e.g. an array list) for processing later, like this:

BufferedReader lineReader = new BufferedReader(new FileReader(filePath)); String lineText = null; List listLines = new ArrayList(); while ((lineText = lineReader.readLine()) != null) < listLines.add(lineText); >lineReader.close();

Using the LineNumberReader class is similar to the BufferedReader class, for example:

String filePath = «Path/To/Your/Text/File.txt»; try < LineNumberReader lineReader = new LineNumberReader(new FileReader(filePath)); String lineText = null; while ((lineText = lineReader.readLine()) != null) < System.out.println(lineReader.getLineNumber() + ": " + lineText); >lineReader.close(); > catch (IOException ex)

Читайте также:  Просмотр кода php страницы

The LineNumberReader class provides the getLineNumber() method which returns the current line number, so we can use it for checking conditions on line numbers, for example:

    Printing only the even lines:

while ((lineText = lineReader.readLine()) != null) < int lineNumber = lineReader.getLineNumber(); if (lineNumber % 2 == 0) < System.out.println(lineNumber + ": " + lineText); >>
while ((lineText = lineReader.readLine()) != null) < int lineNumber = lineReader.getLineNumber(); if (lineNumber >= 50 && lineNumber >

NOTES: The LineNumberReader class also provides the setLineNumber() method but it doesn’t change to the current position in the file stream. It only changes the value that will be returned by the getLineNumber() method.

API References:

Other Java File IO Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

How To Read a File Line-By-Line in Java

How To Read a File Line-By-Line in Java

In this article, you will learn about different ways to use Java to read the contents of a file line-by-line. This article uses methods from the following Java classes: java.io.BufferedReader , java.util.Scanner , Files.readAllLines() , and java.io.RandomAccessFile .

Reading a File Line-by-Line using BufferedReader

You can use the readLine() method from java.io.BufferedReader to read a file line-by-line to String. This method returns null when the end of the file is reached.

Here is an example program to read a file line-by-line with BufferedReader :

package com.journaldev.readfileslinebyline; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFileLineByLineUsingBufferedReader  public static void main(String[] args)  BufferedReader reader; try  reader = new BufferedReader(new FileReader("sample.txt")); String line = reader.readLine(); while (line != null)  System.out.println(line); // read next line line = reader.readLine(); > reader.close(); > catch (IOException e)  e.printStackTrace(); > > > 

Continue your learning with the BufferedReader API Doc (Java SE 8).

Reading a File Line-by-Line using Scanner

You can use the Scanner class to open a file and then read its content line-by-line.

Here is an example program to read a file line-by-line with Scanner :

package com.journaldev.readfileslinebyline; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadFileLineByLineUsingScanner  public static void main(String[] args)  try  Scanner scanner = new Scanner(new File("sample.txt")); while (scanner.hasNextLine())  System.out.println(scanner.nextLine()); > scanner.close(); > catch (FileNotFoundException e)  e.printStackTrace(); > > > 

Continue your learning with the Scanner API Doc (Java SE 8).

Reading a File Line-by-Line using Files

java.nio.file.Files is a utility class that contains various useful methods. The readAllLines() method can be used to read all the file lines into a list of strings.

Here is an example program to read a file line-by-line with Files :

package com.journaldev.readfileslinebyline; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class ReadFileLineByLineUsingFiles  public static void main(String[] args)  try  ListString> allLines = Files.readAllLines(Paths.get("sample.txt")); for (String line : allLines)  System.out.println(line); > > catch (IOException e)  e.printStackTrace(); > > > 

Continue your learning with the Files API Doc (Java SE 8).

Reading a File Line-by-Line using RandomAccessFile

You can use RandomAccessFile to open a file in read mode and then use its readLine method to read a file line-by-line.

Here is an example program to read a file line-by-line with RandomAccessFile :

package com.journaldev.readfileslinebyline; import java.io.IOException; import java.io.RandomAccessFile; public class ReadFileLineByLineUsingRandomAccessFile  public static void main(String[] args)  try  RandomAccessFile file = new RandomAccessFile("sample.txt", "r"); String str; while ((str = file.readLine()) != null)  System.out.println(str); > file.close(); > catch (IOException e)  e.printStackTrace(); > > > 

Continue your learning with the RandomAccessFile API Doc (Java SE 8).

Conclusion

In this article, you learned about different ways to use Java to read the contents of a file line-by-line.

Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью