Java bufferedoutputstream to file

BufferedOutputStream

File Input/Output operations consume a lot of important resources and are time consuming. Hence, writing a chunk of bytes to a file is faster than writing one byte at a time. It speeds up the I/O process.

BufferedOutputStream class is used to create such buffered output stream using which a chunk of bytes stored in the local buffer of BufferedOutputStream, is written out to a file.

Constructors :

File file= new File("D:/Textbook.txt"); FileOutputStream fos= new FileOutputStream(file); BufferedOutputStream fis= new BufferedOutputStream(fos);

Point to remember

FileOutputStream is a subclass of OutputStream

Methods for writing using BufferedOutputStream

Some methods that we generally use while working with BufferedOutputStream are shown in the table below :

Program to write to a file using BufferedOutputStream.

In this code, we are creating a BufferedOutputStream object to write the bytes stored in its local buffer to a file D:/Textbook.txt through OutputStream i.e. FileOutputStream.

//Program to create a BufferedIOutputStream to write(one byte at a time) out to an existing file. import java.io.*; class A < public static void main(String. ar) < String str="Java is the best programming language"; byte b[]=str.getBytes(); try < FileOutputStream fos= new FileOutputStream("D://TextBook.txt"); BufferedOutputStream bos= new BufferedOutputStream(fos); ///A local buffer is created which is big- //enough to hold a chunk of bytes to be //written out to a file TextBook.txt bos.write(b); //writes to local buffer bos.flush(); bos.close(); fos.close(); >catch(IOException e) < System.out.println(e); >> > 

Output is -:

A file called «TextBook.txt» is created in D: drive, with the contents -:
Java is the best programming language

Читайте также:  About filters in java

Program Analysis

  • Calling the constructor of BufferedOutputStream creates a local buffer, big enough to hold a chunk of bytes to be written out to a file.
  • Data is written (one byte at a time) to the buffer of BufferOutputStream by write(int b) method.
  • A chunk of bytes in buffer is written to the file at once by flush() method or close() method.
  • Finally, the opened input streams are closed by close() method to free any connected resources.

Источник

Java bufferedoutputstream to file

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

Класс 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 не добавляет много новой функциональности, он просто оптимизирует действие потока вывода.

Источник

Class BufferedOutputStream

The class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.

Field Summary

Fields declared in class java.io.FilterOutputStream

Constructor Summary

Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.

Method Summary

Writes len bytes from the specified byte array starting at offset off to this buffered output stream.

Methods declared in class java.io.FilterOutputStream

Methods declared in class java.io.OutputStream

Methods declared in class java.lang.Object

Field Details

buf

count

The number of valid bytes in the buffer. This value is always in the range 0 through buf.length ; elements buf[0] through buf[count-1] contain valid byte data.

Constructor Details

BufferedOutputStream

BufferedOutputStream

Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.

Method Details

write

write

Writes len bytes from the specified byte array starting at offset off to this buffered output stream. Ordinarily this method stores bytes from the given array into this stream’s buffer, flushing the buffer to the underlying output stream as needed. If the requested length is at least as large as this stream’s buffer, however, then this method will flush the buffer and write the bytes directly to the underlying output stream. Thus redundant BufferedOutputStream s will not copy data unnecessarily.

flush

Flushes this buffered output stream. This forces any buffered output bytes to be written out to the underlying output stream.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Java bufferedoutputstream to file

The class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.

Field Summary

Fields inherited from class java.io.FilterOutputStream

Constructor Summary

Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.

Method Summary

Writes len bytes from the specified byte array starting at offset off to this buffered output stream.

Methods inherited from class java.io.FilterOutputStream

Methods inherited from class java.lang.Object

Field Detail

buf

count

The number of valid bytes in the buffer. This value is always in the range 0 through buf.length; elements buf[0] through buf[count-1] contain valid byte data.

Constructor Detail

BufferedOutputStream

BufferedOutputStream

Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.

Method Detail

write

write

Writes len bytes from the specified byte array starting at offset off to this buffered output stream. Ordinarily this method stores bytes from the given array into this stream’s buffer, flushing the buffer to the underlying output stream as needed. If the requested length is at least as large as this stream’s buffer, however, then this method will flush the buffer and write the bytes directly to the underlying output stream. Thus redundant BufferedOutputStream s will not copy data unnecessarily.

flush

Flushes this buffered output stream. This forces any buffered output bytes to be written out to the underlying output stream.

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.

Источник

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