Java files read all text

Java files read all text

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

Reading a File into ArrayList in Java

Learn to read all the lines from a file into ArrayList using Java IO APIs, Common IO and Guava classes.

Remember that reading the whole file into memory is recommended only for small text files where we may want to refer to the file content multiple times in the program. In such cases, reading the file multiple times is not an ideal solution. So we must read the file content once in the List, and then refer to it in all the other places in the program.

1. Reading All Lines into ArrayList

To read all the lines from the file, we have multiple efficient solutions that require only a single statement execution. Let us see a few of them.

1.1. Java NIO’s Files.readAllLines()

The readAllLines() method reads all lines from a file. It also closes the file when all bytes have been read or an I/O error, or other runtime exception, is thrown.

try < Listlist = Files.readAllLines( new File("data.txt").toPath(), Charsets.UTF_8 ); > catch (IOException e)

Many times, we may want to process the lines as they are read. In such cases, we can read the file as Stream and apply some intermediate actions on the stream elements as they are processed.

try (Stream stream = Files.lines(Paths.get("data.txt"))) < ArrayListarrayList = stream .collect(Collectors.toCollection(ArrayList::new)); > catch (IOException e)

1.3. Common IO’s FileUtils.readLines()

This method also reads the contents of a file line by line to a List of Strings. The file is always closed after the read operation is finished.

try < Listlines = FileUtils.readLines( new File("data.txt"), StandardCharsets.UTF_8); > catch (IOException e)

This method returns a mutable list of strings that contains all the lines from the file.

Читайте также:  Link rel preload css

For an ImmutableList , use Files.asCharSource(file, charset).readLines() .

try < Listlines = com.google.common.io.Files.readLines( new File("data.txt"), StandardCharsets.UTF_8); > catch (IOException e)

2. Reading File Line by Line and Collect into List

Another way to read all lines in the file is, to read the file one line at a time in a while loop and add it to the List.

This solution presents us the opportunity to perform necessary data sanitization before adding to the list. We can also choose to include or discard the line.

The Scanner is a simple text scanner, used for parsing primitive types and strings, using regular expressions.

We can use the nextLine() method to read an entire line. To check if there is more content in the file, we can use the hasNext() method.

try(Scanner s = new Scanner(new File("data.txt"))) < ArrayListlist = new ArrayList<>(); while (s.hasNext()) < list.add(s.next()); >> catch (FileNotFoundException e)

The BufferedReader class also provides methods, similar to the Scanner class, that can be used to read the line and check for any remaining content in the file.

try (BufferedReader reader = new BufferedReader( new FileReader("data.txt"))) < ArrayListlist = new ArrayList<>(); while (reader.ready()) < list.add(reader.readLine()); >> catch (IOException e)

As shown in the discussed solutions, reading all the lines from a file is not a complex problem to solve. We can decide the solution based on the requirements if there is some intermediate processing required before adding the line to the List or not.

Источник

Reading text files in Java

In Reading text files in Java tutorial we show how to read text files in Java. We use build-in tools including FileReader , InputStreamReader , and Scanner . In addition, we use API Google Guava library.

Google Guava is set of common libraries for Java; the set includes IO API, too.

The following examples use this text file.

The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the course of three days, during the second Persian invasion of Greece.

The file is located in the src/resources/ directory.

Java read text classes

  • java.io.FileReader
  • java.nio.file.Files
  • java.util.Scanner
  • java.io.InputStreamReader
  • com.google.common.io.Files

Java read text file with FileReader

FileReader is a class used for reading character files. It reads text from character files using a default buffer size. Decoding from bytes to characters uses either a specified charset or the platform’s default charset.

Note: In the past, FileReader relied on the default platform’s encoding. Since Java 11, the issue was corrected. It is possible now to explicitly specify the encoding.

package com.zetcode; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; public class FileReaderEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; try (BufferedReader br = new BufferedReader( new FileReader(fileName, StandardCharsets.UTF_8))) < var sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) < sb.append(line); sb.append(System.lineSeparator()); >System.out.println(sb); > > >

The code example reads text from the thermopylae.txt file.

var fileName = "src/resources/thermopylae.txt";

In the fileName variable, we store the path to the file.

try (BufferedReader br = new BufferedReader( new FileReader(fileName, StandardCharsets.UTF_8))) 

The FileReader takes the file name as the first parameter. The second parameter is the charset used. The FileReader is passed to the BufferedReader , which buffers read operations for better performance. This is a try-with-resources statement which ensures that the resource (the buffered reader) is closed at the end of the statement.

var sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) < sb.append(line); sb.append(System.lineSeparator()); >System.out.println(sb);

Printing lines to the console consumes additional resources. Therefore, we use the StringBuilder to build the output string and print it in one operation. This is an optional optimization. The System.lineSeparator returns the system-dependent line separator string.

Java read text file with Files.readAllLines

The Files.readAllLines method reads all lines from a file. This method ensures that the file is closed when all bytes have been read or an exception is thrown. The bytes from the file are decoded into characters using the specified charset.

Note that this method reads the whole file into the memory; therefore, it may not be suitable for very large files.

package com.zetcode; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class ReadAllLinesEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; Listlines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8); for (String line : lines) < System.out.println(line); >> >

The contents of the thermopylae.txt file are read and printed to the console using the Files.readAllLines method.

Reading text file with Java 8 streaming API

Another option to read text files is to use the Java 8 streaming API. The Files.lines reads all lines from a file as a stream. The bytes from the file are decoded into characters using the StandardCharsets.UTF-8 charset.

package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesLinesEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; Files.lines(Paths.get(fileName)).forEachOrdered(System.out::println); >>

The contents of the thermopylae.txt file are read and printed to the console using the Files.lines method.

Java read text file with Scanner

A Scanner is simple text scanner which can parse primitive types and strings using regular expressions.

package com.zetcode; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ScannerEx < public static void main(String[] args) throws FileNotFoundException < var fileName = "src/resources/thermopylae.txt"; try (var scanner = new Scanner(new File(fileName))) < while (scanner.hasNext()) < String line = scanner.nextLine(); System.out.println(line); >> > >

The example reads a text file using a Scanner .

The file is read line by line with the nextLine method.

Java read text file with InputStreamReader

InputStreamReader is a bridge from byte streams to character streams. It reads bytes and decodes them into characters using a specified charset.

package com.zetcode; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; public class InputStreamReaderEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; try (var br = new BufferedReader(new InputStreamReader( new FileInputStream(fileName), StandardCharsets.UTF_8))) < String line; while ((line = br.readLine()) != null) < System.out.println(line); >> > >

The example reads a text file using an InputStreamReader .

try (var br = new BufferedReader(new InputStreamReader( new FileInputStream(fileName), StandardCharsets.UTF_8))) 

The InputStreamReader is created from a FileInputStream , which creates an input stream by opening a connection to an actual file. The InputStreamReader is then passed to a BufferedReader for better efficiency.

Java 7 introduced a more convenient API to work with an InputStreamReader . A new buffered InputStreamReader can be created with Files.newBufferedReader .

package com.zetcode; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; public class InputStreamReaderEx2 < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; var filePath = Paths.get(fileName); try (BufferedReader br = Files.newBufferedReader( filePath, StandardCharsets.UTF_8)) < String line; while ((line = br.readLine()) != null) < System.out.println(line); >> > >

The example reads the thermopylae.txt file with the Files.newBufferedReader method.

Java read text file with Files.readAllBytes

The Files.readAllBytes method reads all the bytes from a file. It ensures that the file is closed when all bytes have been read.

package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class ReadAllBytesEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; var filePath = Paths.get(fileName); byte[] data = Files.readAllBytes(filePath); var content = new String(data); System.out.println(content); >>

The example reads all bytes from a file and passes them to the String constructor.

Java read text with Files.readString

Java 11 introduces a convenient method that allows to read the whole file into a string in one shot.

The Files.readString reads all content from a file into a string, decoding from bytes to characters using the specified or the default (StandardCharsets.UTF_8) charset. It ensures that the file is closed when all content have been read.

package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class ReadFileAsStringEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; var filePath = Paths.get(fileName); var content = Files.readString(filePath); System.out.println(content); >>

The example reads the contents of the thermopylae.txt file into a string a prints it to the terminal.

Java read text file with FileChannel

FileChannel is a channel for reading, writing, mapping, and manipulating a file. The advantages of file channels include reading and writing at a specific position of a file, loading a section of a file, or locking a section of a file.

package com.zetcode; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileChannelEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; try (RandomAccessFile myFile = new RandomAccessFile(fileName, "rw"); FileChannel inChannel = myFile.getChannel()) < ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf); while (bytesRead != -1) < buf.flip(); while (buf.hasRemaining()) < System.out.print((char) buf.get()); >buf.clear(); bytesRead = inChannel.read(buf); > > > >

The example reads the text file with FileChannel .

try (RandomAccessFile myFile = new RandomAccessFile(fileName, "rw"); FileChannel inChannel = myFile.getChannel()) 

A FileChannle is created from a RandomAccessFile .

ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf);

We allocate a buffer and read initial data.

while (bytesRead != -1) < buf.flip(); while (buf.hasRemaining()) < System.out.print((char) buf.get()); >buf.clear(); bytesRead = inChannel.read(buf); >

We read the data into the buffer and write it to the terminal. We use flip to change buffer from reading to writing.

Reading text file with Google Guava

Google Guava is a Java helper library which has IO tools, too. The following two Guava methods would consume a lot of system resources if the file to be read is very large.

  4.0.0 com.zetcode readtextguavaex 1.0-SNAPSHOT UTF-8 12 12   com.google.guava guava 28.0-jre    

This is the Maven POM file.

package com.zetcode; import com.google.common.base.Charsets; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.util.List; public class ReadTextGuavaEx < public static void main(String[] args) throws IOException < var fileName = "src/main/resources/thermopylae.txt"; Listlines = Files.readLines(new File(fileName), Charsets.UTF_8); var sb = new StringBuilder(); for (String line: lines) < sb.append(line); sb.append(System.lineSeparator()); >System.out.println(sb); > >

In the example, we read all of the lines from a file with the Files.readLines method. The method returns a list of strings. A default charset is specified as the second parameter.

In the second example, we use Files.asCharSource .

package com.zetcode; import com.google.common.base.Charsets; import com.google.common.io.Files; import java.io.File; import java.io.IOException; public class ReadTextGuavaEx2 < public static void main(String[] args) throws IOException < var fileName = "src/main/resources/thermopylae.txt"; var charSource = Files.asCharSource(new File(fileName), Charsets.UTF_8).read(); System.out.println(charSource); >>

The Files.asCharSource for reading character data from the given file using the given character set. Its read method reads the contents of this source as a string.

In this article we have read text files in various ways in Java.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

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