Java File Input and Output

In this Java article we want to learn about Java File Input and Output, Java is popular programming language that provides different libraries and tools for working with files. in this article we want to talk that how to read from and write to files using Java file input and output capabilities.

 

 

File Input in Java

Reading data from a file is a common task in many Java applications. Java provides different ways to read data from a file, it depends on structure and size of the data.

 

the best way to read data from a file in Java is using FileInputStream class. this class provides low level interface for reading data from a file byte by byte. this is an example:

In the above example we have created FileInputStream object that opens a file called file.txt for reading. after that we have used a while loop to read the data from the file one byte at a time. read() method of the FileInputStream class returns the next byte of data from the file. loop continues until the read() method returns -1, indicating that the end of the file has been reached.

 

 

File Output in Java

Writing data to a file is another common task in Java programming. Java provides several classes for writing data to file.

most common way to write data to a file in Java is by using FileOutputStream class. this class provides low level interface for writing data to a file byte by byte. 

In the above example we have created FileOutputStream object that opens a file called file.txt for writing. after that we have created byte array the contains the data we want to write. 

 

 

Learn More

Leave a Comment