Use JDK native file operations
In JDK, we can use Java I/O API to manipulate files and folders. The Java I/O API provides many classes and interfaces to manipulate files and folders. Following are some commonly used Java I/O API classes:
- -
java.io.File
Used to represent the path of files and folders, as well as the properties and operations of files and folders. - -
java.io.FileInputStream
Used to read data from a file. - -
java.io.FileOutputStream
Used to write data to a file. - -
java.io.FileReader
Used to read characters from a file. - -
java.io.FileWriter
Used to write characters to a file. - -
java.io.BufferedReader
Used to read text from a character stream. - -
java.io.BufferedWriter
Used to write text to a character stream.
Create a file
In Java, we can create a file using java.io.File
the class . Here is an example:
import java.io.File;
public class FileCreateExample {
public static void main(String[] args) {
File file = new File("test.txt");
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
In this example, we created an File
object and then used createNewFile
the method to create a file named "test.txt". If the file already exists, "File already exists." will be printed.
read file
In Java, we can use java.io.FileInputStream
the class to read data from a file. Here is an example:
import java.io.FileInputStream;
public class FileReadExample {
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("test.txt");
int i;
while ((i = fileInputStream.read()) != -1) {
System.out.print((char) i);
}
fileInputStream.close();
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
In this example, we use FileInputStream
the class to read data from the "test.txt" file. Then, we use while
a loop to read the contents of the file character by character and print it out.
write to file
In Java, we can write data to a file using java.io.FileOutputStream
the class . The following is an example
import java.io.FileOutputStream;
public class FileWriteExample {
public static void main(String[] args) {
try {
FileOutputStream fileOutputStream = new FileOutputStream("test.txt");
String text = "Hello, World!";
byte[] bytes = text.getBytes();
fileOutputStream.write(bytes);
fileOutputStream.close();
System.out.println("Successfully wrote to the file.");
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
In this example, we use FileOutputStream
the class to write the "Hello, World!" string to the "test.txt" file.
Delete Files
In Java, we can delete a file using java.io.File
the class . Here is an example:
import java.io.File;
public class FileDeleteExample {
public static void main(String[] args) {
File file = new File("test.txt");
if (file.delete()) {
System.out.println("File deleted: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
In this example, we created an File
object and then used delete
the method to delete a file named "test.txt".
copy files
In Java, we can use java.io.FileInputStream
the and java.io.FileOutputStream
class to copy files. Here is an example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileCopyExample {
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("test.txt");
FileOutputStream fileOutputStream = new FileOutputStream("test_copy.txt");
byte[] buffer = new byte[1024];
int length;
while ((length = fileInputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
fileInputStream.close();
fileOutputStream.close();
System.out.println("File copied successfully.");
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
In this example, we use FileInputStream
the class to read data from the "test.txt" file, and FileOutputStream
the class to write data to the "test_copy.txt" file.
rename file
In Java, we can rename a file using java.io.File
the class . Here is an example:
import java.io.File;
public class FileRenameExample {
public static void main(String[] args) {
File file = new File("test.txt");
File renamedFile = new File("test_renamed.txt");
if (file.renameTo(renamedFile)) {
System.out.println("File renamed successfully.");
} else {
System.out.println("Failed to rename the file.");
}
}
}
In this example, we create an File
object and use renameTo
the method to rename the "test.txt" file to "test_renamed.txt".
find files
In Java, we can use java.io.File
the class to find files and folders. Here is an example:
import java.io.File;
public class FileSearchExample {
public static void main(String[] args) {
File dir = new File(".");
File[] files = dir.listFiles();
for (File file : files) {
if (file.isFile()) {
System.out.println("File: " + file.getName());
} else if (file.isDirectory()) {
System.out.println("Directory: " + file.getName());
}
}
}
}
In this example, we create an File
object to represent the current directory, then listFiles
use the method to get all the files and folders in the current directory, and use a for loop to print the name of each file and folder.
Using the Apache Commons IO library
In addition to using JDK's native file operation classes, you can also use third-party class libraries for file operations. Apache Commons IO is a very popular Java file operation class library, which provides many useful classes and methods, which can make file operations easier for us. Below is some sample code showing how to use the Apache Commons IO library for file operations.
write to file
Writing to files can be even simpler with the Apache Commons IO library. Here is an example of writing to a file using FileUtils
the class :
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class FileWriteExample {
public static void main(String[] args) {
try {
File file = new File("test.txt");
String text = "Hello, World!";
FileUtils.writeStringToFile(file, text, "UTF-8");
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
In this example, we use FileUtils.writeStringToFile
the method to write a string to a file. This method automatically creates the file, or overwrites the existing file if it already exists.
Delete Files
Deleting files is also very simple using the Apache Commons IO library. Here is an example of using FileUtils
the class to delete a file:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class FileDeleteExample {
public static void main(String[] args) {
File file = new File("test.txt");
try {
FileUtils.forceDelete(file);
System.out.println("File deleted: " + file.getName());
} catch (IOException e) {
System.out.println("Failed to delete the file.");
e.printStackTrace();
}
}
}
In this example, we use FileUtils.forceDelete
the method to delete the file. File
Unlike the method of the class delete
, FileUtils.forceDelete
the method can delete non-empty folders.
copy files
Copying files is also very simple using the Apache Commons IO library. Here is an example of copying files using FileUtils
the class :
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class FileCopyExample {
public static void main(String[] args) {
try {
File srcFile = new File("test.txt");
File destFile = new File("test_copy.txt");
FileUtils.copyFile(srcFile, destFile);
System.out.println("File copied successfully.");
} catch (IOException e)
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
In this example, we use FileUtils.copyFile
the method to copy one file to another. This method will automatically create the target file, if the target file already exists, it will overwrite the existing file.
list files and folders
Listing files and folders is also very simple using the Apache Commons IO library. Here is an example of listing files and folders using FileUtils
the class :
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.Collection;
public class FileSearchExample {
public static void main(String[] args) {
File dir = new File(".");
Collection<File> files = FileUtils.listFilesAndDirs(dir, null, true);
for (File file : files) {
if (file.isFile()) {
System.out.println("File: " + file.getName());
} else if (file.isDirectory()) {
System.out.println("Directory: " + file.getName());
}
}
}
}
In this example, we use FileUtils.listFilesAndDirs
the method to get all the files and folders in the specified directory. This method returns Collection
an File
object that contains all files and folders.
in conclusion
File manipulation in Java is a very common task. JDK provides many useful classes and methods that allow us to easily perform file operations. In addition, there are many third-party libraries that can help us perform file operations more easily, such as Apache Commons IO and so on. Whether you choose to use the JDK or a third-party library, file manipulation is easy.