How to copy a file to a specific directory in Java
To copy a file to a specified directory in Java, you can use the File class and InputStream/OutputStream class in the Java IO library.
Here is a simple example code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopy {
public static void main(String[] args) {
String sourceFilePath = "path/to/source/file";
String destinationFilePath = "path/to/destination/file";
File sourceFile = new File(sourceFilePath);
File destinationFile = new File(destinationFilePath);
try {
copyFile(sourceFile, destinationFile);
System.out.println("文件复制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void copyFile(File source, File destination) throws IOException {
FileInputStream inputStream = new FileInputStream(source);
FileOutputStream outputStream = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
In the code, replace the source file path and destination file path with the actual file paths. Then, copy the file by calling the copyFile method. This method reads data from the source file using FileInputStream and writes it to the destination file using FileOutputStream.
Please ensure that the source file exists and has read permission, and that the target directory exists and has write permission.