要在Java中復(fù)制文件到指定目錄,可以使用Java IO庫(kù)中的File類和InputStream/OutputStream類。
以下是一個(gè)簡(jiǎn)單的示例代碼:
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("文件復(fù)制成功!");
} 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();
}
}
在代碼中,將源文件路徑和目標(biāo)文件路徑替換為實(shí)際的文件路徑。然后,通過(guò)調(diào)用copyFile
方法來(lái)復(fù)制文件。該方法使用FileInputStream從源文件讀取數(shù)據(jù),并使用FileOutputStream將數(shù)據(jù)寫入目標(biāo)文件。
請(qǐng)確保源文件存在,并且具有讀取權(quán)限,目標(biāo)目錄存在并且具有寫入權(quán)限。