-3

我已经尝试了许多来自同一个问题的例子,包括:

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
}

还有其他方法可以复制或修复上述方法吗?

4

3 回答 3

3

With Java 7's standard library, you can use java.nio.file.Files.copy(Path source, Path target, CopyOption... options). No need to add additional dependencies or implement your own.

try {
     Files.copy( Paths.get( sFrom ), 
                 Paths.get( sTo ),
                 StandardCopyOption.REPLACE_EXISTING);
 } catch (IOException e) { 
     // Handle exception
 }
于 2013-04-12T14:03:19.293 回答
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 是副本的名称。

于 2013-04-12T13:58:54.680 回答
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);
        }

   }

}
于 2013-04-12T14:30:21.587 回答