在Java中,可以使用以下方法將文件上傳到指定目錄:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class FileUploader {
public static void uploadFile(File file, String destinationDirectory) throws IOException {
Path destinationPath = new File(destinationDirectory, file.getName()).toPath();
Files.copy(file.toPath(), destinationPath, StandardCopyOption.REPLACE_EXISTING);
}
public static void main(String[] args) {
File fileToUpload = new File("path/to/file.txt");
String destinationDirectory = "path/to/destination/directory";
try {
uploadFile(fileToUpload, destinationDirectory);
System.out.println("File uploaded successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class FileUploader {
public static void uploadFile(File file, String destinationDirectory) throws IOException {
FileUtils.copyFileToDirectory(file, new File(destinationDirectory));
}
public static void main(String[] args) {
File fileToUpload = new File("path/to/file.txt");
String destinationDirectory = "path/to/destination/directory";
try {
uploadFile(fileToUpload, destinationDirectory);
System.out.println("File uploaded successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
無論使用哪種方法,確保目標目錄存在,并具有適當的權限來執行上傳操作。