+ File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy files. +
+
+ Java has several libraries included for file handling, though, they must be imported. Java includes a class called
+ import java.io.File;
+
+ The
+ import java.util.Scanner;
+
+ The
+ import java.io.FileWriter;
+
+ Finally, these last two classes provide error handling and must be used in tandem with the
+ import java.io.IOException;
+
+ import java.io.FileNotFoundException
+
+ Before we can write code that creates a file, we must first import the necessary classes mentioned in the previous section (
+ import java.io.File;
+ import java.io.IOException;
+
+ public class CreateFile {
+ public static void main(String[] args) {
+
+ }
+ }
+
+ Next, within the main function, we will create a
+ File myFile = new File("myfile.txt");
+
+
+ Now that we have created a new
+ First, lets look at the equivalent Python code: +
+ +
+ import os
+
+ filename = "myfile.txt"
+
+ if not os.path.exists(filename):
+ with open(filename, 'x') as f:
+ pass
+ print(f"The file {filename} was created successfully.")
+ else:
+ print(f"The file {filename} already exists.")
+
+ Now, let's look at Java code that accomplishes the same task: +
+ +
+ import java.io.File;
+ import java.io.IOException;
+
+ public class CreateFile {
+ public static void main(String[] args) {
+ if (myFile.createNewFile()) { // If the file was created successfully
+ System.out.println("The file " + myFile.getName() + " was created sucessfully.");
+ } else { // If a file with the file name chosen already exists
+ System.out.println("The file " + myFile.getName() + " already exists.");
+ }
+ }
+ }
+
+ You may have noticed the use of another method from the File class;
+ The code may seem complete at this point, but if you remember from the previous section, error handling using the
+ try {
+ if (myFile.createNewFile()) { // If the file was created successfully
+ System.out.println("The file " + myFile.getName() + " was created sucessfully.");
+ } else { // If a file with the file name chosen already exists
+ System.out.println("The file " + myFile.getName() + " already exists.");
+ }
+ } catch (IOException e) {
+ System.out.println("An error occurred.");
+ e.printStackTrace();
+ }
+
+ The
+ An error occurred.
+ java.io.IOException: Permission denied
+ at java.base/java.io.File.createNewFile(File.java:1040)
+ at CreateFile.main(CreateFile.java:7)
+
+
+ + At this point, the program will function correctly. Let's add the try/catch blocks to the foundational code written before to get a complete program. +
+ ++ First, the equivalent Python code: +
+ +
+ import os
+
+ filename = "myfile.txt"
+
+ try:
+ if not os.path.exists(filename):
+ with open(filename, 'x') as f:
+ pass # Create the file without writing anything
+ print(f"The file {filename} was created successfully.")
+ else:
+ print(f"The file {filename} already exists.")
+ except OSError as e:
+ print("An error occurred.")
+ import traceback
+ traceback.print_exc()
+
+ Now, the completed Java code: +
+ +
+ import java.io.File;
+ import java.io.IOException;
+
+ public class CreateFile {
+ public static void main(String[] args) {
+ try {
+ File myFile = new File("myfile.txt");
+ if (myFile.createNewFile()) { // If the file was created successfully
+ System.out.println("The file " + myFile.getName() + " was created sucessfully.");
+ } else { // If a file with the file name chosen already exists
+ System.out.println("The file " + myFile.getName() + " already exists.");
+ }
+ } catch (IOException e) {
+ System.out.println("An error occurred.");
+ e.printStackTrace();
+ }
+
+ }
+ }
+
+ You may be wondering: "What if I don't want to create a file in the current working directory?" Good question! In Windows environments, you can specify the file path using two back slashes for each back slash in the file path. For each pair of back slashes, the first back slash acts as an escape character. So, if you want to save a file to this directory: +
+ ++ C:\Users\UserName\Documents ++ +
+ The line of code that creates a File object will look like this: +
+ +
+ File myFile = new File("C:\\Users\\UserName\\Documents\\myfile.txt");
+
+ If you are working in a Linux or Apple environment, you can simply use the file path with single forward slashes: +
+ +
+ File myFile = new File("/home/UserName/Documents/myfile.txt");
+
+ The
+ To write to a file, we will need to create a different class. We will do the same setup as the previous section. First, we will import the classes (
+ import java.io.FileWriter;
+ import java.io.IOException;
+
+ public class WriteFile {
+ public static void main(String[] args) {
+
+ }
+ }
+
+ Next, we will create a
+ FileWriter myWriter = new FileWriter("myfile.txt");
+
+ In this next step, we will use the
+ myWriter.write("File successfully updated!");
+ myWriter.close();
+
+ You may have noticed the
+ Next, we will again add the required try/catch blocks utilizing the
+ try:
+ with open("myfile.txt", "w") as my_writer:
+ my_writer.write("File successfully updated!")
+ print("File successfully written to.")
+ except OSError as e:
+ print("An error occurred.")
+ import traceback
+ traceback.print_exc()
+
+ + And the equivalent Java code: +
+ +
+ try {
+ FileWriter myWriter = new FileWriter("myfile.txt");
+ myWriter.write("File successfully updated!");
+ myWriter.close();
+ System.out.println("File successfully written to.");
+ } catch (IOException e) {
+ System.out.println("An error occurred.");
+ e.printStackTrace();
+ }
+
+ And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code: +
+ +
+ try:
+ with open("myfile.txt", "w") as my_writer:
+ my_writer.write("File successfully updated!")
+ print("File successfully written to.")
+ except OSError as e:
+ print("An error occurred.")
+ import traceback
+ traceback.print_exc()
+
+ The completed Java code: +
+ +
+ import java.io.FileWriter;
+ import java.io.IOException;
+
+ public class WriteFile {
+ public static void main(String[] args) {
+ try {
+ FileWriter myWriter = new FileWriter("myfile.txt");
+ myWriter.write("File successfully updated!");
+ myWriter.close();
+ System.out.println("File successfully written to.");
+ } catch (IOException e) {
+ System.out.println("An error occurred.");
+ e.printStackTrace();
+ }
+ }
+ }
+
+ Files in a specific directory can be written to using the same technique as the last section in which file paths are specified, with two back slashes used in Windows environments. +
+ +
+ If a file does not already exist (for example,
+ Speaking of overwriting data, what if we want to append text to the end of any text already in
+ FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode
+
+ Now, when we use
+ import java.io.FileWriter;
+ import java.io.IOException;
+
+ public class WriteFile {
+ public static void main(String[] args) {
+ try {
+ FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode
+ myWriter.write("File successfully updated!");
+ myWriter.close();
+ System.out.println("File successfully written to.");
+ } catch (IOException e) {
+ System.out.println("An error occurred.");
+ e.printStackTrace();
+ }
+ }
+ }
+
+ and then run the program twice, the contents of
+ File successfully updated!File successfully updated!
+
+ This doesn't look very good! There is no space between the first and second sentences! We can make this look a little better by simply adding a space after the exclamation mark in the string: +
+ +
+ myWriter.write("File successfully updated! "); // Added space at end
+ myWriter.close();
+
+ This works fine if you want all text to be on the same line, but what if we want each additional write to appear on a new line? The first solution may be to use the
+ myWriter.write("File successfully updated!\n"); // Added newline character
+ myWriter.close();
+
+ This would work fine most of the time, but older Windows programs and operating systems use the
+ myWriter.write("File successfully updated!" + System.lineseparator()); // Added newline character
+ myWriter.close();
+
+ Running either variation used for adding new lines twice will result in the following contents in myfile.txt: +
+ +
+ File successfully updated!
+ File successfully updated!
+
+ Let's take a look at how we can use Java to read file contents. We'll start again with library imports and building a class, this time importing the Scanner and FileNotFoundException classes. We will call this class ReadFile: +
+ +
+ import java.io.File;
+ import java.io.FileNotFoundException;
+ import java.util.Scanner
+
+ public class ReadFile {
+ public static void main(String[] args) {
+
+ }
+ }
+
+ We will then create a new File object exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader: +
+ +
+ File myFile = new File("myfile.txt");
+ Scanner fileReader = new Scanner(myFile);
+
+ The myFile File object we created on the first line was passed to the Scanner object created on the second line. +
++ The next lines consist of a while loop that reads each line of the file passed to the Scanner object and reads them. First, a Python code example. A for loop is used instead in the Python example: +
+ +
+ with open("filename.txt", "r") as file_reader:
+ for line in file_reader:
+ print(line.strip())
+
+ + The equivalent Java code: +
+ +
+ while (fileReader.hasNextLine()) {
+ String data = fileReader.nextLine();
+ System.out.println(data);
+ }
+ fileReader.close();
+
+ The
+ Alternatively, the following code can be used to store the all lines of myfile.txt to one variable: +
+ +
+ String data = "";
+ while (fileReader.hasNextLine()) {
+ data = data + fileReader.nextLine() + System.lineSeparator();
+ }
+ System.out.println(data);
+ fileReader.close();
+
+ Pay close attention to the details of this code.
+ Using the second method of storing all file contents to one file, the resulting full code including try/catch blocks (this time using FileNotFoundException instead of IOException) will look something like this. First, the Python code: +
+ +
+ try:
+ with open("myfile.txt", "r") as file_reader:
+ data = ""
+ for line in file_reader:
+ data += line # line already includes the newline character
+ print(data)
+ except FileNotFoundError as e:
+ print("An error occurred.")
+ import traceback
+ traceback.print_exc()
+
+
+ + And the Java equivalent: +
+ +
+ import java.io.File;
+ import java.io.FileNotFoundException;
+ import java.util.Scanner
+
+ public class ReadFile {
+ public static void main(String[] args) {
+ try {
+ File myFile = new File("myfile.txt");
+ Scanner fileReader = new Scanner(myFile);
+ String data = "";
+ while (fileReader.hasNextLine()) {
+ data = data + fileReader.nextLine() + System.lineSeparator();
+ }
+ System.out.println(data);
+ fileReader.close();
+ } catch (FileNotFoundException e) {
+ System.out.println("An error occurred.");
+ e.printStackTrace();
+ }
+ }
+ }
+
+ In this code, we simply print the contents of the file to the console, but it is easy to imagine how the
+ Finally, we will take a look at using Java to delete files. This one is pretty straight-forward and follows the structure used to create files. This time, however, try/catch blocks are not needed for the program to compile. We will call this class DeleteFile. The completed code should look something like this. +
+ +
+ import java.io.File;
+
+ public class DeleteFile {
+ public static void main(String[] args) {
+ File myFile = new File("myfile.txt");
+ if (myFile.delete()) {
+ System.out.println("Deleted " + myFile.getName());
+ } else {
+ System.out.println("File could not be deleted.");
+ }
+ }
+ }
+
+ This is almost identical to the code within the try block of the CreateFile class we made earlier. The main difference is the use of the