Read full file in java

How to Read Files in Java

Throughout the tutorial, we are using a file stored in the src directory where the path to the file is src/file.txt .

Store several lines of text in this file before proceeding.

Note: You have to properly handle the errors when using these implementations to stick to the best coding practices.

Reading Text Files in Java with BufferedReader

The BufferedReader class reads a character-input stream. It buffers characters in a buffer with a default size of 8 KB to make the reading process more efficient. If you want to read a file line by line, using BufferedReader is a good choice.

BufferedReader is efficient in reading large files.

import java.io.*; public class FileReaderWithBufferedReader < public static void main(String[] args) throws IOExceptionbufferedReader.close(); > > 

The readline() method returns null when the end of the file is reached.

Reading UTF-8 Encoded File in Java with BufferedReader

We can use the BufferedReader class to read a UTF-8 encoded file.

This time, we pass an InputStreamReader object when creating a BufferedReader instance.

import java.io.*; public class EncodedFileReaderWithBufferedReader < public static void main(String[] args) throws IOException < String file = "src/fileUtf8.txt"; BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String curLine; while ((curLine = bufferedReader.readLine()) != null)< //process the line as you require System.out.println(curLine); >> > 

Using Java Files Class to Read a File

Java Files class, introduced in Java 7 in Java NIO, consists fully of static methods that operate on files.

Using Files class, you can read the full content of a file into an array. This makes it a good choice for reading smaller files.

Let’s see how we can use Files class in both these scenarios.

Reading Small Files in Java with Files Class

The readAllLines() method of the Files class allows reading the whole content of the file and stores each line in an array as strings.

You can use the Path class to get the path to the file since the Files class accepts the Path object of the file.

import java.io.IOException; import java.nio.file.*; import java.util.*; public class SmallFileReaderWithFiles < public static void main(String[] args) throws IOException < String file = "src/file.txt"; Path path = Paths.get(file); Listlines = Files.readAllLines(path); > > 

You can use readAllBytes() to retrieve the data stored in the file to a byte array instead of a string array.

byte[] bytes = Files.readAllBytes(path); 

Reading Large Files in Java with Files Class

If you want to read a large file with the Files class, you can use the newBufferedReader() method to obtain an instance of BufferedReader class and read the file line by line using a BufferedReader .

import java.io.*; import java.nio.file.*; public class LargeFileReaderWithFiles < public static void main(String[] args) throws IOException < String file = "src/file.txt"; Path path = Paths.get(file); BufferedReader bufferedReader = Files.newBufferedReader(path); String curLine; while ((curLine = bufferedReader.readLine()) != null)< System.out.println(curLine); >bufferedReader.close(); > > 

Reading Files with Files.lines()

Java 8 introduced a new method to the Files class to read the whole file into a Stream of strings.

import java.io.IOException; import java.nio.file.*; import java.util.stream.Stream; public class FileReaderWithFilesLines < public static void main(String[] args) throws IOException < String file = "src/file.txt"; Path path = Paths.get(file); Streamlines = Files.lines(path); lines.forEach(s -> System.out.println(s)); lines.close(); > > 

Reading Text Files in Java with Scanner

The Scanner class breaks the content of a file into parts using a given delimiter and reads it part by part. This approach is best suited for reading content that is separated by a delimiter.

For example, the Scanner class is ideal for reading a list of integers separated by white spaces or a list of strings separated by commas.

The default delimiter of the Scanner class is whitespace. But you can set the delimiter to another character or a regular expression. It also has various next methods, such as next() , nextInt() , nextLine() , and nextByte() , to convert content into different types.

import java.io.IOException; import java.util.Scanner; import java.io.File; public class FileReaderWithScanner < public static void main(String[] args) throws IOException< String file = "src/file.txt"; Scanner scanner = new Scanner(new File(file)); scanner.useDelimiter(" "); while(scanner.hasNext())< String next = scanner.next(); System.out.println(next); >scanner.close(); > > 

In the above example, we set the delimiter to whitespace and use the next() method to read the next part of the content separated by whitespace.

Reading an Entire File

You can use the Scanner class to read the entire file at once without running a loop. You have to pass “\\Z” as the delimiter for this.

scanner.useDelimiter("\\Z"); System.out.println(scanner.next()); scanner.close(); 

Conclusion

As you saw in this tutorial, Java offers many methods that you can choose from according to the nature of the task at your hand to read text files. You can use BufferedReader to read large files line by line.

If you want to read a file that has its content separated by a delimiter, use the Scanner class.

Also you can use Java NIO Files class to read both small and large files.

Источник

Read full file in java

  • 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

Источник

How to read a File in Java

How to read a File in Java

In this article, you’ll learn how to read a text file or binary (image) file in Java using various classes and utility methods provided by Java like BufferedReader , LineNumberReader , Files.readAllLines , Files.lines , BufferedInputStream , Files.readAllBytes , etc.

Let’s look at each of the different ways of reading a file in Java with the help of examples.

Java read file using BufferedReader

BufferedReader is a simple and performant way of reading text files in Java. It reads text from a character-input stream. It buffers characters to provide efficient reading.

import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class BufferedReaderExample  public static void main(String[] args)  Path filePath = Paths.get("demo.txt"); Charset charset = StandardCharsets.UTF_8; try (BufferedReader bufferedReader = Files.newBufferedReader(filePath, charset))  String line; while ((line = bufferedReader.readLine()) != null)  System.out.println(line); > > catch (IOException ex)  System.out.format("I/O error: %s%n", ex); > > >

Java read file line by line using Files.readAllLines()

Files.readAllLines() is a utility method of the Java NIO’s Files class that reads all the lines of a file and returns a List containing each line. It internally uses BufferedReader to read the file.

import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class FilesReadAllLinesExample  public static void main(String[] args)  Path filePath = Paths.get("demo.txt"); Charset charset = StandardCharsets.UTF_8; try  ListString> lines = Files.readAllLines(filePath, charset); for(String line: lines)  System.out.println(line); > > catch (IOException ex)  System.out.format("I/O error: %s%n", ex); > > >

Java read file line by line using Files.lines()

Files.lines() method reads all the lines from a file as a Stream . You can use Stream API methods like forEach , map to work with each line of the file.

import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FilesLinesExample  public static void main(String[] args)  Path filePath = Paths.get("demo.txt"); Charset charset = StandardCharsets.UTF_8; try  Files.lines(filePath, charset) .forEach(System.out::println); > catch (IOException ex)  System.out.format("I/O error: %s%n", ex); > > >

Java read file line by line using LineNumberReader

LineNumberReader is a buffered character-stream reader that keeps track of line numbers. You can use this class to read a text file line by line.

import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class LineNumberReaderExample  public static void main(String[] args)  Path filePath = Paths.get("demo.txt"); Charset charset = StandardCharsets.UTF_8; try(BufferedReader bufferedReader = Files.newBufferedReader(filePath, charset); LineNumberReader lineNumberReader = new LineNumberReader(bufferedReader))  String line; while ((line = lineNumberReader.readLine()) != null)  System.out.format("Line %d: %s%n", lineNumberReader.getLineNumber(), line); > > catch (IOException ex)  System.out.format("I/O error: %s%n", ex); > > >

Java read binary file (image file) using BufferedInputStream

All the examples presented in this article so far read textual data from a character-input stream. If you’re reading a binary data such as an image file then you need to use a byte-input stream.

BufferedInputStream lets you read raw stream of bytes. It also buffers the input for improving performance.

import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; public class BufferedInputStreamImageCopyExample  public static void main(String[] args)  try(InputStream inputStream = Files.newInputStream(Paths.get("sample.jpg")); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); OutputStream outputStream = Files.newOutputStream(Paths.get("sample-copy.jpg")); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream))  byte[] buffer = new byte[4096]; int numBytes; while ((numBytes = bufferedInputStream.read(buffer)) != -1)  bufferedOutputStream.write(buffer, 0, numBytes); > > catch (IOException ex)  System.out.format("I/O error: %s%n", ex); > > >

Java read file into []byte using Files.readAllBytes()

If you want to read the entire contents of a file in a byte array then you can use the Files.readAllBytes() method.

import com.sun.org.apache.xpath.internal.operations.String; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesReadAllBytesExample  public static void main(String[] args)  try  byte[] data = Files.readAllBytes(Paths.get("demo.txt")); // Use byte data > catch (IOException ex)  System.out.format("I/O error: %s%n", ex); > > >

Источник

Читайте также:  Java stream concat three streams
Оцените статью