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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.FileInputStream; import java.io.IOException; public class Main { public static void main(String[] args) { try (FileInputStream fileInputStream = new FileInputStream("file.txt")) { int data; while ((data = fileInputStream.read()) != -1) { // Print the data to the console System.out.print((char) data); } } catch (IOException e) { e.printStackTrace(); } } } |
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.
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.
1 2 3 4 5 6 |
try (FileOutputStream fileOutputStream = new FileOutputStream("file.txt")) { byte[] data = "Hello, world".getBytes(); fileOutputStream.write(data); } catch (IOException e) { e.printStackTrace(); } |
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