Have troubles with Java file handling or handling files in Java? This will be a one-stop solution to all your troubles.

Today we are going to cover-

  • File class in Java
  • How to create Files in Java
  • How to write in Files using Java file handling
  • How to read existing Files | Java
  • Delete Files in Java
  • BONUS: School Report System (simple file handling project in java)

File class in Java

Available in java.io package File class helps us to deal with files in Java. Let’s say we want to create an output file for our program and save it in our system for future use.

Or we have a large input data file which we need to parse and then process to get some useful insights.

How to do it?

Well, the java File class comes in handy with a lot of useful methods –

methods for read and write operation

File Handling in Java Example Programs

Below are various file handler java program examples-

How to create Files in Java

To understand this, let’s take a simple exercise. We have to write a Java program to print all prime numbers from 1 to 100 and store the output in a text file.

No need to learn the syntax, just understand how each line works. Later if needed you can always look up for the code here at Letstacle.

Let’s dig into Java file handling.


import java.io.File;
import java.io.IOException;

public class FileHandling {
  public static void main(String[] args) {
    File myFile = new File("output.txt");
    try {
      if (myFile.createNewFile()) { // createNewFile() returns true if file creation was successful
        System.out.println("File created: " + myFile.getName());
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Output
File created: output.txt

Java file handling

Refresh the project after file handler java

If you are using eclipse, try refreshing the project folder to see the output file.

In line 6, we have created the file called ‘output.txt’ using the code File myFile = new File("output.txt");. Here, we have simply created an object of the File class and passed the file name as an argument to the constructor.

Now, using the object of this class (here called ‘myFile’) we can call the available methods like createNewFile(). This method returns true if file creation was successful. Therefore, we apply simple if-else logic to display messages accordingly.

But we must be careful because some of these methods throw some specific Exceptions. In this case, IOException. This exception is shown when we have provided an invalid path to create a file (see line 6).
io exception in java file handling
For instance, File myFile = new File("/invalid/output.txt");. This statement will throw the IOException because we don’t have any folder called ‘invalid’ in the specified directory. We must handle these according to our requirements. In the given code we have surrounded the createNewFile() method with a try-catch block.

How to write in Files using Java file handling

Well, we are done with file creation now let’s add the code to write something in it.


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileHandling {
  public static void main(String[] args) {
    // create file
    File myFile = new File("output.txt");
    try {
      if (myFile.createNewFile()) { // createNewFile() returns true if file creation was successful
        System.out.println("File created: " + myFile.getName());
      } else {
        System.out.println("File already exists.");
      }
    
    // write to a file
      FileWriter myWriter = new FileWriter(myFile);
      myWriter.write("I wrote something using FileWriter in Java..");
      myWriter.close();
      System.out.println("File writing Successful!!");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Output
File already exists.
File writing Successful!!

We have only added 4 new lines 16-19. That’s all we need to write something in a file using java. Java file handling can be that simple!!

First, we have created an object of the FileWriter class using the same File object ‘myFile’ – FileWriter myWriter = new FileWriter(myFile);.Now, myWriter.write("I wrote something using FileWriter in Java..");, the write method is required to write the text in the file.

Good for us, we don’t need to explicitly create a file to write something in it. Hey, FileWriter is smart enough to create a new File if not created already. So, simplifying the above code, we get,


import java.io.FileWriter;
import java.io.IOException;

public class FileHandling {
  public static void main(String[] args) {
    try {
      // create and write to a file
      FileWriter myWriter = new FileWriter("output.txt");
      myWriter.write("I wrote something using FileWriter in Java..");
      myWriter.close();
      System.out.println("File writing Successful!!");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Output
File writing Successful!!

Now, we are all set. Let’s add the logic to write all prime numbers from 1 to 100.


import java.io.FileWriter;
import java.io.IOException;

public class FileHandling {
  // method to check if n is prime or not?
  public static boolean isPrime(int n) {
    if(n<=2)
      return false;
    for(int i=2; i<Math.sqrt(n); i++) {
      if(n%i == 0)
        return false;
    }
    return true;
  }
  // main method
  public static void main(String[] args) {
    try {
      // create and write to a file
      FileWriter myWriter = new FileWriter("output.txt");

      // logic
      for(int i=1; i<100; i++) {
        if(isPrime(i))
          myWriter.write(i+" ");
      }

      // close writer | task complete
      myWriter.close();
      System.out.println("File writing Successful!!");
    } catch (IOException e) {
      // exception occured
      e.printStackTrace();
    }
  }
}

Output
File writing Successful!!
output.txt
5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Here, we have added a new method called isPrime(int n). This returns true if n is a prime number. Hence, we run a loop from 1 to 100 checking all the numbers and writing them in our file ‘output.txt’ only if they are prime.

How to read existing Files?

Want to print the output file in your console? Alright, here’s the code.


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileReading {
	public static void main(String[] args) {
		try {
			File myFile = new File("output.txt"); // file object
			Scanner sc = new Scanner(myFile); // scanner object
			while (sc.hasNextLine()) {
				System.out.println(sc.nextLine());
			}
			sc.close();
		} catch (FileNotFoundException e) {
			// print exception details
			e.printStackTrace();
		}
	}
}

Output
5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
The above code simply copies all the content of the ‘output.txt’ file and prints it in the console line by line. Let’s take a look at steps required.

  1. Create a File object with the file name that you want to read.
  2. Create a Scanner object by passing the file object to the constructor.
  3. Now loop through the file contents line by line using sc.hasNextLine() which returns true if the file has a line left to be read. We can read these lines using sc.nextLine() which returns a String containing the content of the current line and moves the scanner cursor to the next line.

Note: Be very careful with the file name. If the wrong name is provided, a new File will get created and you will see no output in the console as the new file will be empty.

Delete Files in Java

Now that you have learned how to work with files in java, it is time to clean up by deleting the file that we just created- ‘output.txt’. However, it’s really simple. Let’s jump into the code right away.


import java.io.File;

public class FileHandling {
	public static void main(String[] args) {
		File myFile = new File("output.txt"); // file object
		if (myFile.delete()) { // returns true if file delete successful
			System.out.println("Deleted file: " + myFile.getName());
		} else {
			System.out.println("Failed to delete the file.");
		}
	}
}

output
Deleted file: output.txt

School Report System (simple file handling project in java)

Well, now that we have learnt the basics of file handling, let’s try and build a simple project where we can find some real-time use cases of java file handling.

Project Description: Here we have to build a school report system, where we have been provided with a file ‘input.txt’. This file contains scores of each student in each row in the following format: [name physics chemistry mathematics english].

We have to process the data and sort them in descending order [top scorer will be in the first row], and save the output in ‘report.txt’ with each row in the following format: [name total_score]. The total score will be calculated as the average marks in all 4 subjects: [(phy+chem+math+eng)/4].

Sample Input File

john 80 74 54 99
lucy 90 91 99 79
brad 100 80 82 77
jimmy 88 86 83 63
susy 77 67 65 100
toto 56 67 66 54

Sample Output File

lucy 89.75
brad 84.75
jimmy 80.0
john 76.75
susy 77.25
toto 60.75

Before you check the solution, I shall highly recommend you try it out in your own favourite IDE and try to use the above code snippets to complete the task. Still, facing problems? No worries, you almost got it.

Here’s the code for help.


class Student {
	String name;
	int phy;
	int chem;
	int math;
	int eng;
	double total;

	public Student(String name, int phy, int chem, int math, int eng) {
		this.name = name;
		this.phy = phy;
		this.chem = chem;
		this.math = math;
		this.eng = eng;
		this.total = 0;
	}
}

public class SchoolReportSystem {
	public static void main(String[] args) {
		try {
			File myFile = new File("input.txt"); // file object
			Scanner sc = new Scanner(myFile); // scanner object

			// step 1: create the student list by reading the input file
			List studentList = new ArrayList<>();
			while (sc.hasNextLine()) {
				String data[] = sc.nextLine().split(" ");
				String name = data[0];
				int phy = Integer.parseInt(data[1]);
				int chem = Integer.parseInt(data[2]);
				int math = Integer.parseInt(data[3]);
				int eng = Integer.parseInt(data[4]);
				studentList.add(new Student(name, phy, chem, math, eng));
			}

			// step 2: calculate total score (phy+chem+math+eng)/4
			for (Student s : studentList) {
				s.total = (s.phy + s.chem + s.math + s.eng) / 4.0;
			}

			// step 3: sort the list in descending order of total score
			Collections.sort(studentList, (s1, s2) -> (int) (s2.total - s1.total));

			// step 4: print output in a file
			FileWriter myWriter = new FileWriter("output.txt");
			for (Student s : studentList) {
				myWriter.write(s.name + " " + s.total + "\n");
			}
			myWriter.close();
			System.out.println("Report Generation Successful !!");

			sc.close();
		} catch (FileNotFoundException e) {
			// print exception details
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Output
Report Generation Successful !!
output.txt
lucy 89.75
brad 84.75
jimmy 80.0
john 76.75
susy 77.25
toto 60.75

read and write txt file java programming output

Code Explanation

First, we have created a Student class with the following attributes: String name; int phy; int chem; int math; int eng; double total;. Also, add a constructor to initialize all values except total [total will be calculated using the subject marks].

We have used the same snippet to read the input file. now use the split function on each line with space (” “) as a delimiter. This will return an array of Strings.

For instance, the first line [john 80 74 54 99] when processed by split(" ") returns {"john","80","74","54","99"}.

Using this array we can fetch all the required student details as follows:

String data[] = sc.nextLine().split(" ");
String name = data[0];
int phy = Integer.parseInt(data[1]);
int chem = Integer.parseInt(data[2]);
int math = Integer.parseInt(data[3]);
int eng = Integer.parseInt(data[4]);

Therefore we can easily create a list of students List studentList = new ArrayList<>();, and add each student’s details using: studentList.add(new Student(name, phy, chem, math, eng));. Now we have a studentList to work with.

Simply loop through the studentList and calculate the total for each student. Then sort according to the total value.

All we need to do that is Collections.sort(studentList, (s1, s2) -> (int) (s2.total - s1.total));.

Java provides Collections class in java.util.Collections package to help us sort custom data types (like Student) with our own logic.

All we have to do is provide the Collection [List studentList] and the comparator logic.

Still, having issues? Read Collections in Java | Java Collections Framework.

The last step to finish our task is to write the sorted list in output.txt. Simply refer to ‘How to write in Files using Java file handling’ discussed above.

Hope you are now ready to handle files in java with ease. Do not refrain from trying the chat box to reach out to us.