java無(wú)法復(fù)制文件怎么解決

小億
109
2024-04-12 10:15:25

在Java中復(fù)制文件可以使用以下方法:

  1. 使用Java IO庫(kù)中的FileInputStream和FileOutputStream類進(jìn)行復(fù)制操作。示例代碼如下:
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) {
        File sourceFile = new File("source.txt");
        File destFile = new File("dest.txt");

        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(destFile)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            System.out.println("File copied successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 使用Apache Commons IO庫(kù)中的FileUtils類進(jìn)行復(fù)制操作。示例代碼如下:
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class FileCopy {
    public static void main(String[] args) {
        File sourceFile = new File("source.txt");
        File destFile = new File("dest.txt");

        try {
            FileUtils.copyFile(sourceFile, destFile);
            System.out.println("File copied successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

這兩種方法都是常用的文件復(fù)制方法,你可以根據(jù)自己的需求選擇適合的方法來(lái)實(shí)現(xiàn)文件復(fù)制操作。

0