- Reading a File Line by Line in Java
- How To Read a File Line-By-Line in Java
- Reading a File Line-by-Line using BufferedReader
- Reading a File Line-by-Line using Scanner
- Reading a File Line-by-Line using Files
- Reading a File Line-by-Line using RandomAccessFile
- Conclusion
- Load file java line by line
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
Reading a File Line by Line in Java
In this Java tutorial, we will learn to read a file line by line using various methods. We will also learn to iterate through lines and filter the file content based on some conditions.
1. Reading with Stream of Lines
In this example, we will read the file contents one line at a time using Java Stream API and fetch each line one at a time and check it for word «password» .
Path filePath = Paths.get("c:/temp", "data.txt"); //try-with-resources try (Stream lines = Files.lines( filePath )) < lines.forEach(System.out::println); >catch (IOException e)
We can also use the Files.readAllLines() method that reads all lines from a file into a List. By default, bytes from the file are decoded into characters using the UTF-8 charset .
Path filePath = Paths.get("c:/temp", "data.txt"); List lines = Files.readAllLines(filePath);
2. Reading and Filtering the Content
In this example, we will read the file content as a stream of lines as. Then we will filter all lines which have the word “password” in them.
For filtering, we are passing a lambda expression, that is an instance of a Predicate, to the filter() method.
Path filePath = Paths.get("c:/temp", "data.txt"); try (Stream lines = Files.lines(filePath)) < ListfilteredLines = lines .filter(s -> s.contains("password")) .collect(Collectors.toList()); filteredLines.forEach(System.out::println); > catch (IOException e)
We are reading the content of the given file and checking if any line contains word «password» then print it.
3. Reading a File Line by Line using FileReader
Till Java 7, we could read a file using FileReader in various ways.
File file = new File("c:/temp/data.txt"); try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr);) < String line; while ((line = br.readLine()) != null) < System.out.println(line); >> catch (IOException e)
One of the simplest solutions is to use the Google Guava’s Files class its method readLines().
try < Listlines = com.google.common.io.Files.readLines(file, Charset.defaultCharset()); > catch (IOException e)
If we want to process the lines as they are read, we can use a LineProcessor. For example, in the below code, we are capitalizing the lines as they are read.
// With LineProcessor LineProcessor> lineProcessor = new LineProcessor<>() < final Listresult = new ArrayList<>(); @Override public boolean processLine(final String line) throws IOException < result.add(StringUtils.capitalize(line)); return true; // keep reading >@Override public List getResult() < return result; >>; try < Listlines = com.google.common.io.Files .asCharSource(file, Charset.defaultCharset()) .readLines(lineProcessor); > catch (IOException e)
5. Commons IO’s FileUtils.readLines()
Similar to Guava, Apache Commons IO library has FileUtils class that provides a single statement solution for reading the file content in lines. The file is always closed at the end of the operation.
try < Listlines = FileUtils.readLines(file, Charset.defaultCharset()); > catch (IOException e)
That’s all for Java example to read a file line by line. Please put your questions in the comments section.
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.
Load file java line by line
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter