Java read file in one line

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.

Читайте также:  Html 5 speed reading

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

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.

Источник

Read a File to String in Java

Learn to read a text file into String in Java. Following examples use Files.readAllBytes() , Files.lines() (to read line by line) and FileReader and BufferedReader to read a file to String.

1. Using Files.readString() – Java 11

With the new method readString() introduced in Java 11, it takes only a single line to read a file’s content into String using the UTF-8 charset .

  • In case of any error during the read operation, this method ensures that the file is properly closed.
  • It throws OutOfMemoryError if the file is extremely large, for example, larger than 2GB .
Path filePath = Path.of("c:/temp/demo.txt"); String content = Files.readString(fileName);

2. Using Files.lines() – Java 8

The lines() method reads all lines from a file into a Stream. The Stream is populated lazily when the stream is consumed.

  • Bytes from the file are decoded into characters using the specified charset.
  • The returned stream contains a reference to an open file. The file is closed by closing the stream.
  • The file contents should not be modified during the reading process, or else the result is undefined.
Path filePath = Path.of("c:/temp/demo.txt"); StringBuilder contentBuilder = new StringBuilder(); try (Stream stream = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8)) < stream.forEach(s ->contentBuilder.append(s).append("\n")); > catch (IOException e) < //handle exception >String fileContent = contentBuilder.toString();

3. Using Files.readAllBytes() – Java 7

The readAllBytes() method reads all the bytes from a file into a byte[]. Do not use this method for reading large files.

This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. After reading all the bytes, we pass those bytes to String class constructor to create a new String.

Path filePath = Path.of("c:/temp/demo.txt"); String fileContent = ""; try < byte[] bytes = Files.readAllBytes(Paths.get(filePath)); fileContent = new String (bytes); >catch (IOException e) < //handle exception >

4. Using BufferedReader – Java 6

If you are still not using Java 7 or later, then use BufferedReader class. Its readLine() method reads the file one line at a time and returns the content .

Path filePath = Path.of("c:/temp/demo.txt"); String fileContent = ""; StringBuilder contentBuilder = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(filePath))) < String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) < contentBuilder.append(sCurrentLine).append("\n"); >> catch (IOException e) < e.printStackTrace(); >fileContent = contentBuilder.toString();

We can use the utility classes provided by the Apache Commons IO library. The FileUtils.readFileToString() is an excellent way to read a whole file into a String in a single statement.

File file = new File("c:/temp/demo.txt"); String content = FileUtils.readFileToString(file, "UTF-8");

Guava also provides Files class that can be used to read the file content in a single statement.

File file = new File("c:/temp/demo.txt"); String content = com.google.common.io.Files.asCharSource(file, Charsets.UTF_8).read();

Use any of the above-given methods for reading a file into a string using Java.

Источник

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