我已经尝试了很多来自同一个问题的例子,包括:
IOUtils.copy();
(复制是一种不存在的方法)
Files.copy(source, target, REPLACE_EXISTING);
(REPLACE_EXISTING“找不到符号”)
FileUtils.copyFile();
(FileUtils不存在)
使用它们的问题在括号内。
以下是最常用的复制方法的代码:
import static java.nio.file.Files;
public void Install()
{
CrtFol();
CrtImgFol();
CrtSaveFol();
CrtSaveFile();
open.runmm();
//I have added the import for "Files"
Files.copy(img1, d4, REPLACE_EXISTING);
//Compiler says "Cannot find symbol" when I go over REPLACE_EXISTING
//img1 is a File and d4 is a File as a directory
}
是否有其他方法可以复制或修复上述方法?
答案 0 :(得分:3)
使用Java 7的标准库,您可以使用java.nio.file.Files.copy(Path source, Path target, CopyOption... options)。无需添加其他依赖项或实现自己的依赖项。
try {
Files.copy( Paths.get( sFrom ),
Paths.get( sTo ),
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
// Handle exception
}
答案 1 :(得分:1)
不确定Java是否确实有任何要复制文件的内容。最简单的方法是将文件转换为字节流,然后将此流写入另一个文件。像这样:
InputStream inStream = null;
OutputStream outStream = null;
File inputFile =new File("inputFile.txt");
File outputFile =new File("outputFile.txt");
inStream = new FileInputStream(inputFile);
outStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int fileLength;
while ((fileLength = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, fileLength );
}
inStream.close();
outStream.close();
其中inputFile是要从中复制的文件,outputFile是副本的名称。
答案 2 :(得分:1)
我使用此代码:
import java.io.*;
public class CopyTest {
public CopyTest() {
}
public static void main(String[] args) {
try {
File stockInputFile = new File("C://test.txt");
File StockOutputFile = new File("C://output.txt");
FileInputStream fis = new FileInputStream(stockInputFile);
FileOutputStream fos = new FileOutputStream(StockOutputFile);
int count = 0;
while((count = fis.read()) > -1){
fos.write(count);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
System.err.println("FileStreamsReadnWrite: " + e);
} catch (IOException e) {
System.err.println("FileStreamsReadnWrite: " + e);
}
}
}