Bufferedreader to stream java

Bufferedreader to stream java

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

BufferedReader in = new BufferedReader(new FileReader("foo.in"));

will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.

Field Summary

Fields inherited from class java.io.Reader

Constructor Summary

Method Summary

Methods inherited from class java.io.Reader

Methods inherited from class java.lang.Object

Constructor Detail

BufferedReader

BufferedReader

Method Detail

read

read

  • The specified number of characters have been read,
  • The read method of the underlying stream returns -1 , indicating end-of-file, or
  • The ready method of the underlying stream returns false , indicating that further input requests would block.

readLine

public String readLine() throws IOException

Reads a line of text. A line is considered to be terminated by any one of a line feed (‘\n’), a carriage return (‘\r’), or a carriage return followed immediately by a linefeed.

skip

ready

Tells whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready.

markSupported

public boolean markSupported()

mark

Marks the present position in the stream. Subsequent calls to reset() will attempt to reposition the stream to this point.

reset

close

Closes the stream and releases any system resources associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.

lines

Returns a Stream , the elements of which are lines read from this BufferedReader . The Stream is lazily populated, i.e., read only occurs during the terminal stream operation. The reader must not be operated on during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined. After execution of the terminal stream operation there are no guarantees that the reader will be at a specific position from which to read the next character or line. If an IOException is thrown when accessing the underlying BufferedReader , it is wrapped in an UncheckedIOException which will be thrown from the Stream method that caused the read to take place. This method will return a Stream if invoked on a BufferedReader that is closed. Any operation on that stream that requires reading from the BufferedReader after it is closed, will cause an UncheckedIOException to be thrown.

Читайте также:  Бесконечный вывод в питоне

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Источник

How to read a File line by line in Java 8 ? BufferedReader lines() + Stream Examples

Hello guy, if you are wondering how to read a file line by line in Java but not sure which class to use then you have come to the right place. Earlier, I have showed you how to read Excel file in Java using Apache POI API and in this article, I am going to tell you about a useful method from BufferedReader class, the lines() method which can be used to read a file line by line. The BufferedReader.lines() is kind of interesting, letting you turn a BufferedReader into a java.util.Stream in Java 8. This is a very powerful thing as it allows you to tread a file as a stream and then you can apply all sorts of Stream methods like map, count, flatMap, filter, distinct, etc to apply the powerful transformation. We will actually see examples of those in this article by finding out the longest line from the file and printing each line of the file.

How to use BufferedReader.lines() + Stream in Java to Read a File Line by Line

Here are some useful examples by using the BufferedReader class and its lines() method which is newly added in Java 8 to find out the number of total lines from the file and printing the file line by line.

1. Print out the number of lines in a file:

This Java program can be used to find out the total number of lines in a given file using BufferedReader.lines() method which basically returns a stream and then we can use the count() method of Stream class to find out the total number of elements.

public static void main(String[] args) < try (BufferedReader reader = Files.newBufferedReader( Paths.get("myfile.txt"), StandardCharsets.UTF_8)) < System.out.println(reader.lines().count()); > catch (IOException ex) < >>

2. Print out all the lines:

This code can be used to read all the lines of a file in Java using BufferedReader.lines() method as shown below. You can see that we are using the forEach() method and method reference to print each line this is possible because the lines() method of BufferedReader returns a Stream and then you can use any Stream method to perform useful operations like counting or printing it element by element.

public static void main(String[] args) < try (BufferedReader reader = Files.newBufferedReader( Paths.get("myfile.txt"), StandardCharsets.UTF_8)) < reader.lines().forEach(System.out::println); > catch (IOException ex) < >>

3. Print out the longest line in a file

This example is a little bit elaborated and shows the power of Stream in Java. You can see that we first get the stream of lines using the lines() method and then mapped each line to their length to find out the longest line of the file.

public static void main(String[] args) < try (BufferedReader reader = Files.newBufferedReader( Paths.get("myfile.txt"), StandardCharsets.UTF_8)) < System.out.println(reader .lines() .mapToInt(String::length) .max() .getAsInt()); > catch (IOException ex) < >>

This is remarkable and considers doing this prior to Java 8, it wasn’t that easy and that’s why I really love streams. If you want to learn more about such gems, I highly recommend you to join these best Java Lambda and Functional Programming courses to learn Stream and Lambdas in-depth and become a better Java developer.

Читайте также:  Распределение коши в python

BufferedReader.lines() + Stream Examples in Java 8

Java Program to use BufferedReader.lines() method

The file used in this example is a Java manifest file created by Netbeans IDE for this program. Since the file is already in the classpath, we can access it by just specifying its name instead of the full path. The lines() method of BufferedReader returns a Stream with the lines read from this reader.

The best part of this method is that stream is lazily populated, only at the time of doing a terminal operation like forEach() for printing lines or count() to count the total number of lines.

manifest.mf
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build

import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; /** * Java Program to count number of lines in a file, * print each line of file and * find length of longest line in file. * * @author Javin */ public class BufferedReaderJava8Demo< public static void main(String args[]) < // Using BufferedReader lines() method to print number of // lines in a file try (BufferedReader reader = Files.newBufferedReader( Paths.get("manifest.mf"), StandardCharsets.UTF_8)) < long totalLinesInFile = reader.lines().count(); System.out.println("Total number of lines in file is : " + totalLinesInFile); > catch (IOException ex) < ex.printStackTrace(); > // BufferedReader Example to print all lines of a file in Java 8 try (BufferedReader reader = Files.newBufferedReader( Paths.get("manifest.mf"), StandardCharsets.UTF_8)) < System.out.println("Printing all lines in file manifest.mf using Java 8 streams"); reader.lines().forEach(System.out::println); > catch (IOException ex) < ex.printStackTrace(); > // BufferedReader lines() Examples in Java 8 // Let's find length of longest line in file try (BufferedReader reader = Files.newBufferedReader( Paths.get("manifest.mf"), StandardCharsets.UTF_8)) < long longestLineInFile = reader.lines() .mapToInt(String::length) .max() .getAsInt(); System.out.println("Length of longest line in file : " + longestLineInFile); > catch (IOException ex) < ex.printStackTrace(); > > > Output Total number of lines in file is : 3 Printing all lines in file manifest.mf using Java 8 streams Manifest-Version: 1.0 X-COMMENT: Main-Class will be added automatically by build Length of longest line in file : 58

Don’t be surprised by seeing the total number of lines in the file manifest.mf as 3, because every Java manifest file contains an empty line at the bottom. Though you see only two lines, in reality, it is three lines, which is also picked by Java.

Читайте также:  Передача аргументов методу java

In the next example also this is evident because you can see an empty line after «X-COMMENT». Last example of BufferedReader prints the length of the longest line in a file, which is the second line, 58 characters long.

That’s all about how to use BufferedReader in Java 8. By looking at these examples you can easily realize that Java 8 has put enormous power into BufferedReader. Now you can do a lot of things with files and text in only a couple of lines.

The last example shows the true power of Java 8, imagine how would you find the length of the longest line in a File before Java 8. Once you do that, just think again that what if a file is 4GB or 10GB large in size. In Java 8, you can use the parallelStream() instead of the stream() to process large files using multiple threads without writing any additional code.

  • How to sort the map by keys in Java 8? (example)
  • 5 Books to Learn Java 8 from Scratch (books)
  • What is the default method in Java 8? (example)
  • How to use Stream class in Java 8 (tutorial)
  • 10 Free Courses to learn Spring Framework for Beginners (courses)
  • How to convert List to Map in Java 8 (solution)
  • Top 5 Courses to learn Java 8 in depth (courses)
  • How to join String in Java 8 (example)
  • Top 5 Courses to become a full-stack Java developer (courses)
  • How to use filter() method in Java 8 (tutorial)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • Difference between abstract class and interface in Java 8? (answer)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to use peek() method in Java 8 (example)
  • How to sort the may by values in Java 8? (example)
  • 10 examples of Options in Java 8? (example)
  • 5 Courses to learn Functional Programming in Java (courses)

P. S. — If you are impressed with how Java 8 and Stream API makes coding easier in Java and want to learn Stream API in depth then you can also checkout this list of best Stream API online courses for Java developers. It contains best online courses to learn Stream API from Udemy and Pluralsight.

Источник

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