需要注意的是,拷贝前需要对源文件及目标路径做检查,如果源文件或目标路径不存在,会报 NullPointerException 异常。

    1. import java.io.FileInputStream;
    2. import java.io.FileOutputStream;
    3. import java.io.IOException;
    4. public class Main {
    5. public static void main(String[] args) {
    6. // 文件路径
    7. String srcPath = "./write.txt";
    8. String toPath = "./write_copy.txt";
    9. FileInputStream fis = null;
    10. FileOutputStream fos = null;
    11. try {
    12. // 创建流对象
    13. fis = new FileInputStream(srcPath);
    14. fos = new FileOutputStream(toPath);
    15. // buffer 提高读取效率
    16. byte[] buf = new byte[1024];
    17. int readLen = 0;
    18. // 读取到 buffer
    19. while ((readLen = fis.read(buf)) != -1) {
    20. // 写入文件
    21. fos.write(buf, 0, readLen);
    22. }
    23. System.out.println("拷贝成功");
    24. } catch (IOException e) {
    25. e.printStackTrace();
    26. } finally {
    27. // 关闭流
    28. try {
    29. fis.close();
    30. fos.close();
    31. } catch (IOException e) {
    32. e.printStackTrace();
    33. }
    34. }
    35. }
    36. }