Java File Handling

File Handling in Java includes creating, reading, and writing a file. It also includes deleting a file. To work on files in Java, we have the File class. It is part of the following package, which you need to import while working on the File class:

Create a File in Java

To create a File in Java, use the createNewFile() method of the File class in Java. First, import the required package:

Let’s say the name of the file we want to create is myfile.txt at the following location. Use the double backslash in Windows for the path as shown below:

Let us now see an example to create a file in Java:

Output

The file gets created at the location. The file is empty since we did not add any text to it:

Create a File in Java

Write to a File in Java

To write to a File in Java, use the write() method of the FileWriter class. First, import the required package:

Let us now see the Java program to write text to the above file myfile.txt:

Output

The myfile.txt file is now having the following text as shown below:

Write to a File in Java

Read a File in Java

To read a File in Java, use the nextLine() method of the Scanner class. First, import the required package:

We will read the above myfile.txt with the following text:

Read a File in Java

Let us now see the example to read the above file:

Output


If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Java Threading
Java Exception Handling
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading