Read and write file using byte stream in java I/O

Monday, December 28th, 2015 (0 Comment)

To read and write file, then need to ceate a Byte stream associated with the file indicated FileInputStream and FileOutputStream. To open a file, simply create an object of this class, need to open the file name parameter in the constructor. When opening files, reading and writing data on file is normally done through the methods provided in the stream.

Create source.txt file with the following content:

Libraries necessary to read and write file

1. Reading data from file

Open a file for reading data FileInputStream(String fileName) throws FileNotFoundException. If the file does not exist, then thrown out FileNotFoundException

Reading data: Using methods read(), int read( ) throws IOException: read each byte from the file and returns the value of bytes read. Returns -1 if the end of file, and thrown IOException when reading error.

Close file: Using methods close(), void close( ) throws IOException: after the work is complete to need close the file to free up system resources allocated to file.

Example: Displays the contents of a file named source.txt to save at D:\lvtutorial\source.txt

Output:

2. Writing data to file (write file)

Open a file for writing data FileOutputStream(String fileName) throws FileNotFoundException. If the file is not created then thrown out FileNotFoundException.

Writing data to file: Using methods write(), void write(int byteval) throws IOException: record a byte determined by parameters ByVal into files, and IOException thrown when an error record.

Close file: Using methods close(), void close( ) throws IOException: after the work is complete to need close the file to free up system resources allocated to file.

Example: copy content from a text file to a orther text file.

Result: the program will copy the contents of the file D:\lvtutorial\source.txt and write to a new file D:\lvtutorial\dest.txt

3. Reading and writing binary data

To read and write file binary value of the data type in Java, we use the DataInputStream and DataOutputStream. You can search in the internet to understand and clearly about these class.

Example: use DataOutputStream and DataInputStream to write and read these different data types on file.

Output:

The data recorded to the file at D:\\lvtutorial\\testdata

Reading and outputting results to Screen Console:

Tags: , , ,

Related Posts

core java
Export Crystal Report with Subreport in java
core java
Convert xml to object java and vice versa
core java
Java basic tutorial on lvtutorial.com
core java
Java hibernate manytomany to manage user role

Related Posts

core java
Export Crystal Report with Subreport in java
core java
Convert xml to object java and vice versa
core java
Java basic tutorial on lvtutorial.com
core java
Java hibernate manytomany to manage user role

Leave a Reply

Your email address will not be published. Required fields are marked *