Buffered streams in java

Read and write to files with buffered streams in Java

File buffering is a mechanism where the data is read/written into a buffer memory area rather than directly on to disk. This hugely improves the I/O performance when reading or writing files large files since the application doesn’t have to wait for the disk read or write to finish. File buffering is implemented in Java using four streams — BufferedInputStream, BufferedOutputStream, BufferedReader and BufferedWriter. The difference between these buffered streams are BufferedInputStream and BufferedOutputStream are byte streams while BufferedReader and BufferedWriter are character streams. Byte streams read and write data of 8-bit size each at a time. Characters streams are used specifically for character data as it converts the data to local character set. Here is two example programs that shows file read and write using buffered streams.

File copy using Buffered streams

This program copies the file named file1.txt to another file named file1_copy.txt using BufferedInputStream and BufferedOutputStream classes. The program creates a buffered input stream with the source file and a buffered output stream with the destination file. Input stream is read byte by byte and written to the output stream inside a while loop until EOF is reached. Any bytes that remain on the output buffer should be flused out to the disk and the the input and output streams are closed inside a finally block.

import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class BufferedFileIO < public static void main(String[] args) throws IOException < BufferedInputStream bis = null; BufferedOutputStream bos = null; FileInputStream fis = null; FileOutputStream fos = null; try < fis = new FileInputStream("file1.txt"); bis = new BufferedInputStream( fis); fos = new FileOutputStream("file1_copy.txt"); bos = new BufferedOutputStream(fos); int b; while ((b = bis.read()) != -1) < bos.write(b); >bos.flush(); > catch(IOException ex) < System.err.println(ex.getMessage()); >finally < if(fis!=null) fis.close(); if(bis!=null) bis.close(); if(fos!=null) fos.close(); if(bos!=null) bos.close(); >> >

Output text file to console

In this second example the program creates a buffered character input stream for the UTF-8 encoded text file named Japanese.txt, reads each charaacter until EOF and prints the characters to the console.

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedFileIO2 < public static void main(String[] args) throws IOException < BufferedReader br = null; FileReader fr =null; try < fr = new FileReader("japanese.txt"); br = new BufferedReader(fr); int c; while ((c = br.read()) != -1) < System.out.print((char)c); >> catch(IOException ex) < System.err.println(ex.getMessage()); >finally < if(fr!=null) fr.close(); if(br!=null) br.close(); >> >

Источник

Читайте также:  Css custom checkbox without label

Buffered Streams

Most of the examples we’ve seen so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.

To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

A program can convert an unbuffered stream into a buffered stream using the wrapping idiom we’ve used several times now, where the unbuffered stream object is passed to the constructor for a buffered stream class. Here’s how you might modify the constructor invocations in the CopyCharacters example to use buffered I/O:

inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));

There are four buffered stream classes used to wrap unbuffered streams: BufferedInputStream and BufferedOutputStream create buffered byte streams, while BufferedReader and BufferedWriter create buffered character streams.

Flushing Buffered Streams

It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer.

Some buffered output classes support autoflush, specified by an optional constructor argument. When autoflush is enabled, certain key events cause the buffer to be flushed. For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format . See Formatting for more on these methods.

To flush a stream manually, invoke its flush method. The flush method is valid on any output stream, but has no effect unless the stream is buffered.

Источник

Java Guides

In unbuffered I/O, each read or writes request is handled directly by the underlying OS. This can make a program much less efficient since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.

To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

BufferedOutputStream Class

Java BufferedOutputStream class is used for buffering an output stream. It internally uses a buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.

BufferedOutputStream Class Example

package com.javaguides.javaio.fileoperations.examples; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class BufferedOutputStreamExample < public static void main(String[] args) < File file = new File("C:/Project_Work/workspace/java-io-guide/sample.txt"); String content = "This is the text content"; try (OutputStream out = new FileOutputStream(file); BufferedOutputStream bout = new BufferedOutputStream(out);) < // if file doesn't exists, then create it if (!file.exists()) < file.createNewFile(); > // get the content in bytes bout.write(content.getBytes()); > catch (IOException e) < e.printStackTrace(); > > >

BufferedInputStream Class

Java BufferedInputStream class is used to read information from the stream. It internally uses the buffer mechanism to make the performance fast.

  • When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained input stream, many bytes at a time.
  • When a BufferedInputStream is created, an internal buffer array is created.

BufferedInputStream Example

package com.javaguides.javaio.fileoperations.examples; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; public class BufferedInputStreamExample < public static void main(String[] args) < try( FileInputStream fin=new FileInputStream("D:\\testout.txt"); BufferedInputStream bin=new BufferedInputStream(fin); )< int i; while((i=bin.read())!=-1)< System.out.print((char)i); > > catch (IOException e) < e.printStackTrace(); > > >

BufferedWriter Class

Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance fast. It inherits Writer class. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings.

BufferedWriter Class Example

Let’s see the simple example of writing the data to a text file sample.txt using Java BufferedWriter.

package com.javaguides.javaio.fileoperations.examples; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferedWriterExample < public static void main(String[] args) < try (FileWriter writer = new FileWriter("D:\\sample.txt"); BufferedWriter buffer = new BufferedWriter(writer);) < buffer.write("Welcome to JavaGuides."); System.out.println("Success"); > catch (IOException e) < e.printStackTrace(); > > >

BufferedReader Class

Java BufferedReader class is used to read the text from a character-based input stream. It can be used to read data line by line by readLine() method. It makes the performance fast. It inherits Reader class.

BufferedReader Class Example

package com.javaguides.javaio.fileoperations.examples; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderExample < public static void main(String[] args) < try (FileReader fr = new FileReader("C:/Project_Work/sample.txt"); BufferedReader br = new BufferedReader(fr);) < int i; while ((i = br.read()) != -1) < System.out.print((char) i); > > catch (IOException e) < e.printStackTrace(); > > >

Источник

Buffered streams in java

Для оптимизации операций ввода-вывода используются буферизуемые потоки. Эти потоки добавляют к стандартным специальный буфер в памяти, с помощью которого повышается производительность при чтении и записи потоков.

Класс BufferedInputStream

Класс BufferedInputStream накапливает вводимые данные в специальном буфере без постоянного обращения к устройству ввода. Класс BufferedInputStream определяет два конструктора:

BufferedInputStream(InputStream inputStream) BufferedInputStream(InputStream inputStream, int bufSize)

Первый параметр — это поток ввода, с которого данные будут считываться в буфер. Второй параметр — размер буфера.

Например, буферизируем считывание данных из потока ByteArrayInputStream:

import java.io.*; public class Program < public static void main(String[] args) < String text = "Hello world!"; byte[] buffer = text.getBytes(); ByteArrayInputStream in = new ByteArrayInputStream(buffer); try(BufferedInputStream bis = new BufferedInputStream(in))< int c; while((c=bis.read())!=-1)< System.out.print((char)c); >> catch(Exception e) < System.out.println(e.getMessage()); >System.out.println(); > >

Класс BufferedInputStream в конструкторе принимает объект InputStream . В данном случае таким объектом является экземпляр класса ByteArrayInputStream .

Как и все потоки ввода BufferedInputStream обладает методом read() , который считывает данные. И здесь мы считываем с помощью метода read каждый байт из массива buffer.

Фактические все то же самое можно было сделать и с помощью одного ByteArrayInputStream, не прибегая к буферизированному потоку. Класс BufferedInputStream просто оптимизирует производительность при работе с потоком ByteArrayInputStream. Естественно вместо ByteArrayInputStream может использоваться любой другой класс, который унаследован от InputStream.

Класс BufferedOutputStream

Класс BufferedOutputStream аналогично создает буфер для потоков вывода. Этот буфер накапливает выводимые байты без постоянного обращения к устройству. И когда буфер заполнен, производится запись данных.

BufferedOutputStream определяет два конструктора:

BufferedOutputStream(OutputStream outputStream) BufferedOutputStream(OutputStream outputStream, int bufSize)

Первый параметр — это поток вывода, который унаследован от OutputStream, а второй параметр — размер буфера.

Рассмотрим на примере записи в файл:

import java.io.*; public class Program < public static void main(String[] args) < String text = "Hello world!"; // строка для записи try(FileOutputStream out=new FileOutputStream("notes.txt"); BufferedOutputStream bos = new BufferedOutputStream(out)) < // перевод строки в байты byte[] buffer = text.getBytes(); bos.write(buffer, 0, buffer.length); >catch(IOException ex) < System.out.println(ex.getMessage()); >> >

Класс BufferedOutputStream в конструкторе принимает в качестве параметра объект OutputStream — в данном случае это файловый поток вывода FileOutputStream. И также производится запись в файл. Опять же BufferedOutputStream не добавляет много новой функциональности, он просто оптимизирует действие потока вывода.

Источник

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