Basics of Java File Handling
Basics of Java File Handling
File Handling
1 1
ClickHandling
File to edit Master title style
these operations:
• Open File
• Read File
• Write to File
• Close File
2 2
Click File
Java to edit
Handling
Master title style
The File class from the java.io package, allows us to work with files. To
use the File class, import the class from the java.io package and create an
import java.io.File;
The File class has many useful methods for creating and getting information
about files. For example:
Method Name Type Description
canRead() Boolean Check whether the file is readable or not
canWrite() Boolean Check whether the file is writable or not
createNewFile() Boolean Create an empty file
delete() Boolean Delete file
exists() Boolean Check whether the file exists
getName() String Returns the file name
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Return the size of file in bytes
list() String[] Returns an array of files in the directory
mkdir() Boolean Create directory 4 4
Click Create
Java to edit File
Master title style
To create new file in java, you can use the createNewFile() method in the
File class. This method returns boolean value: true, if the file was created
6 6
Click Create
Java to edit File
Master title style
In the given code snippet, notice that the method is enclosed in a try catch block.
occurs.
7 7
Click to
Write toedit
File Master title style
To write data to a file, we will use the FileWriter class together with its write()
method to write data to the file we created. When you are done writing to the file,
writer.close();
8 8
Click to edit Master title style
import java.io.FileWriter;
import java.io.IOException;
// write to file
public class FileApp {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("FileName.txt");
writer.write("Java example of writing data to file.");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException ex) {
System.out.println("An error occurred: " + ex.getMessage());
}
}
}
9 9
Click to
Read File
edit Master title style
class from the java.io package and the Scanner class. We will use the Scanner
class to read the contents of the file. Think of it as getting input data from the
1010
Click to edit Master title style
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
// read contents from file
public class FileApp {
public static void main(String[] args) {
try {
File file = new File("FileName.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException ex) {
System.out.println("An error occurred: " + ex.getMessage());
}
}
}
1111
Click to edit
Example of Getting
Master File
titleInformation
style
import java.io.File;
To delete file in Java, we will use the delete() method in the File class.
import java.io.File;
1414