Read file with bufferedreader 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.

Читайте также:  Close http connection java

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.

Источник

BufferedReader и BufferedWriter

Java-университет

Java класс BufferedReader читает текст из потока ввода символов, буферизуя прочитанные символы, чтобы обеспечить эффективное считывание символов, массивов и строк. Можно указать в конструкторе вторым параметром размер буфера.

BufferedReader и BufferedWriter - 1

 BufferedReader(Reader in) // Создает буферный поток ввода символов, который использует размер буфера по умолчанию. BufferedReader(Reader in, int sz) // Создает буферный поток ввода символов, который использует указанный размер. 
 close() // закрыть поток mark(int readAheadLimit) // отметить позицию в потоке markSupported() // поддерживает ли отметку потока int read() // прочитать буфер int read(char[] cbuf, int off, int len) // прочитать буфер String readLine() // следующая строка boolean ready() // может ли поток читать reset() // сбросить поток skip(long n) // пропустить символы 
 import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileReaderExample < public static void main(String[] args) < String inputFileName = "file.txt"; try (BufferedReader reader = new BufferedReader(new FileReader(inputFileName))) < String line; while ((line = reader.readLine()) != null) < System.out.println(line + "\n"); >> catch (IOException e) < e.printStackTrace(); >> > 

Java класс BufferedWriter записывает текст в поток вывода символов, буферизуя записанные символы, чтобы обеспечить эффективную запись символов, массивов и строк. Можно указать в конструкторе вторым параметром размер буфера. Конструкторы:

 BufferedWriter(Writer out) // Создает буферный поток вывода символов, который использует размер буфера по умолчанию. BufferedWriter(Writer out, int sz) // Создает буферный поток вывода символов, который использует указанный размер. 
 close() // закрыть поток flush() // передать данные из буфера во Writer newLine() // перенос на новую строку write(char[] cbuf, int off, int len) // запись в буфер write(int c) // запись в буфер write(String s, int off, int len) // запись в буфер 
 import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class FileWritterExample < public static void main(String[] args) < String outputFileName = "file.txt"; String[] array = < "one", "two", "three", "four" >; try (BufferedWriter writter = new BufferedWriter(new FileWriter(outputFileName))) < for (String value : array) < writter.write(value + "\n"); >> catch (IOException e) < e.printStackTrace(); >> > 

FileWriter сразу записывает данные на диск и каждый раз к нему обращается, буфер работает как обертка и ускоряет работу приложения. Буфер будет записывать данные в себя, а потом большим куском файлы на диск. Считываем данные с консоли и записываем в файл:

 import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class ConsoleReaderExample < public static void main(String[] args) < String outputFileName = "file.txt"; try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) < try (BufferedWriter writter = new BufferedWriter(new FileWriter(outputFileName))) < String line; while (!(line = reader.readLine()).equals("exit")) < // Прерывание цикла при написании строки exit writter.write(line); >> > catch (IOException e) < e.printStackTrace(); >> > 

Источник

Java read text file

Java read text file

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

There are many ways to read a text file in java. Let’s look at java read text file different methods one by one.

Java read text file

java read file, java read text file

There are many ways to read a text file in java. A text file is made of characters, so we can use Reader classes. There are some utility classes too to read a text file in java.

  1. Java read text file using Files class
  2. Read text file in java using FileReader
  3. Java read text file using BufferedReader
  4. Using Scanner class to read text file in java

Now let’s look at examples showing how to read a text file in java using these classes.

Java read text file using java.nio.file.Files

We can use Files class to read all the contents of a file into a byte array. Files class also has a method to read all lines to a list of string. Files class is introduced in Java 7 and it’s good if you want to load all the file contents. You should use this method only when you are working on small files and you need all the file contents in memory.

String fileName = "/Users/pankaj/source.txt"; Path path = Paths.get(fileName); byte[] bytes = Files.readAllBytes(path); List allLines = Files.readAllLines(path, StandardCharsets.UTF_8); 

Read text file in java using java.io.FileReader

You can use FileReader to get the BufferedReader and then read files line by line. FileReader doesn’t support encoding and works with the system default encoding, so it’s not a very efficient way of reading a text file in java.

String fileName = "/Users/pankaj/source.txt"; File file = new File(fileName); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; while((line = br.readLine()) != null) < //process the line System.out.println(line); >

Java read text file using java.io.BufferedReader

BufferedReader is good if you want to read file line by line and process on them. It’s good for processing the large file and it supports encoding also. BufferedReader is synchronized, so read operations on a BufferedReader can safely be done from multiple threads. BufferedReader default buffer size is 8KB.

String fileName = "/Users/pankaj/source.txt"; File file = new File(fileName); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, cs); BufferedReader br = new BufferedReader(isr); String line; while((line = br.readLine()) != null) < //process the line System.out.println(line); >br.close(); 

Using scanner to read text file in java

If you want to read file line by line or based on some java regular expression, Scanner is the class to use. Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. The scanner class is not synchronized and hence not thread safe.

Path path = Paths.get(fileName); Scanner scanner = new Scanner(path); System.out.println("Read text file using Scanner"); //read line by line while(scanner.hasNextLine()) < //process each line String line = scanner.nextLine(); System.out.println(line); >scanner.close(); 

Java Read File Example

Here is the example class showing how to read a text file in java. The example methods are using Scanner, Files, BufferedReader with Encoding support and FileReader.

package com.journaldev.files; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; 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; import java.util.Scanner; public class JavaReadFile < public static void main(String[] args) throws IOException < String fileName = "/Users/pankaj/source.txt"; //using Java 7 Files class to process small files, get complete file data readUsingFiles(fileName); //using Scanner class for large files, to read line by line readUsingScanner(fileName); //read using BufferedReader, to read line by line readUsingBufferedReader(fileName); readUsingBufferedReaderJava7(fileName, StandardCharsets.UTF_8); readUsingBufferedReader(fileName, StandardCharsets.UTF_8); //read using FileReader, no encoding support, not efficient readUsingFileReader(fileName); >private static void readUsingFileReader(String fileName) throws IOException < File file = new File(fileName); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; System.out.println("Reading text file using FileReader"); while((line = br.readLine()) != null)< //process the line System.out.println(line); >br.close(); fr.close(); > private static void readUsingBufferedReader(String fileName, Charset cs) throws IOException < File file = new File(fileName); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, cs); BufferedReader br = new BufferedReader(isr); String line; System.out.println("Read text file using InputStreamReader"); while((line = br.readLine()) != null)< //process the line System.out.println(line); >br.close(); > private static void readUsingBufferedReaderJava7(String fileName, Charset cs) throws IOException < Path path = Paths.get(fileName); BufferedReader br = Files.newBufferedReader(path, cs); String line; System.out.println("Read text file using BufferedReader Java 7 improvement"); while((line = br.readLine()) != null)< //process the line System.out.println(line); >br.close(); > private static void readUsingBufferedReader(String fileName) throws IOException < File file = new File(fileName); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; System.out.println("Read text file using BufferedReader"); while((line = br.readLine()) != null)< //process the line System.out.println(line); >//close resources br.close(); fr.close(); > private static void readUsingScanner(String fileName) throws IOException < Path path = Paths.get(fileName); Scanner scanner = new Scanner(path); System.out.println("Read text file using Scanner"); //read line by line while(scanner.hasNextLine())< //process each line String line = scanner.nextLine(); System.out.println(line); >scanner.close(); > private static void readUsingFiles(String fileName) throws IOException < Path path = Paths.get(fileName); //read file to byte array byte[] bytes = Files.readAllBytes(path); System.out.println("Read text file using Files class"); //read file to String list @SuppressWarnings("unused") ListallLines = Files.readAllLines(path, StandardCharsets.UTF_8); System.out.println(new String(bytes)); > > 

The choice of using a Scanner or BufferedReader or Files to read file depends on your project requirements. For example, if you are just logging the file, you can use Files and BufferedReader. If you are looking to parse the file based on a delimiter, you should use Scanner class. Before I end this tutorial, I want to mention about RandomAccessFile . We can use this to read text file in java.

RandomAccessFile file = new RandomAccessFile("/Users/pankaj/Downloads/myfile.txt", "r"); String str; while ((str = file.readLine()) != null) < System.out.println(str); >file.close(); 

That’s all for java read text file example programs.

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

Источник

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