Java File Input and Output

In this Java tutorial 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 you can read from a file in Java and how you can 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 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 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.

 

 

 

 

This will be the result, make sure that you have added file in your working directory.

Java File Input and Output
Java File Input and Output

 

 

 

File Output in Java

Writing data to a file is another common task in Java programming. Java provides different 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. 

Subscribe and Get Free Video Courses & Articles in your Email

 

Leave a Comment

Share via
Copy link
Powered by Social Snap
×