代码之家  ›  专栏  ›  技术社区  ›  Student

复制文件的本机JDK代码

  •  2
  • Student  · 技术社区  · 16 年前

    是否有本地JDK代码来复制文件(缓冲区、流或其他内容)?

    4 回复  |  直到 13 年前
        1
  •  2
  •   Michael Borgwardt    13 年前

    如果“原生”是指“Java标准API的一部分”(而不是平台依赖代码),它通常被称为“Java世界中的“本地”),而“复制文件”的意思是“单一方法,它采用文件和目标路径并生成文件内容的副本”,不,在标准API中没有这样的方法。你必须打开一个 InputStream 和一个 OutputStream (也可以提高效率 FileChannel s)并使用缓冲区传输字节。方便的单一调用方法位于 Apache Commons IO .

    更新: 自Java 7以来,文件复制功能已成为标准API的一部分。 java.nio.file.Files

        2
  •  3
  •   user177800    16 年前

    这是自JDK 1.4及更高版本以来复制文件的首选方法

    public static void copyFile(final File sourceFile, final File destFile) throws IOException
    {
        if (!destFile.exists())
        {
            destFile.createNewFile();
        }
    
        FileChannel source = null;
        FileChannel destination = null;
        try
        {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            destination.transferFrom(source, 0, source.size());
        }
        finally
        {
           source.close();
           destination.close();
        }
    }
    

    public abstract long transferFrom(ReadableByteChannel src, long position, long count) throws IOException

    …这种方法很有潜力 比简单的循环更有效 从该通道读取并写入 目标频道。许多操作 系统可以直接传输字节 从文件系统缓存到 目标通道没有实际 复制它们。…

        4
  •  0
  •   Alan    15 年前

    另外,JDK7在java.nio.file.files中定义了几种复制方法,包括将文件复制到流中或从流中复制文件。