Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java IO将一个文件复制到另一个文件_Java_File_File Io_Io_Java Io - Fatal编程技术网

java IO将一个文件复制到另一个文件

java IO将一个文件复制到另一个文件,java,file,file-io,io,java-io,Java,File,File Io,Io,Java Io,我有两个Java.io.File对象file1和file2。我想将内容从文件1复制到文件2。有没有一种标准方法可以做到这一点,而不必创建一个读取file1并写入file2的方法呢?没有。每个长期使用Java的程序员都有自己的实用工具带,其中包括这样一种方法。这是我的 public static void copyFileToFile(final File src, final File dest) throws IOException { copyInputStreamToFile(ne

我有两个Java.io.File对象file1和file2。我想将内容从文件1复制到文件2。有没有一种标准方法可以做到这一点,而不必创建一个读取file1并写入file2的方法呢?没有。每个长期使用Java的程序员都有自己的实用工具带,其中包括这样一种方法。这是我的

public static void copyFileToFile(final File src, final File dest) throws IOException
{
    copyInputStreamToFile(new FileInputStream(src), dest);
    dest.setLastModified(src.lastModified());
}

public static void copyInputStreamToFile(final InputStream in, final File dest)
        throws IOException
{
    copyInputStreamToOutputStream(in, new FileOutputStream(dest));
}


public static void copyInputStreamToOutputStream(final InputStream in,
        final OutputStream out) throws IOException
{
    try
    {
        try
        {
            final byte[] buffer = new byte[1024];
            int n;
            while ((n = in.read(buffer)) != -1)
                out.write(buffer, 0, n);
        }
        finally
        {
            out.close();
        }
    }
    finally
    {
        in.close();
    }
}

不,没有内置的方法可以做到这一点。最接近您想要完成的是
FileOutputStream
中的
transferFrom
方法,如下所示:

  FileChannel src = new FileInputStream(file1).getChannel();
  FileChannel dest = new FileOutputStream(file2).getChannel();
  dest.transferFrom(src, 0, src.size());

不要忘了处理异常,并在
最后关闭
块中的所有内容。

如果您想变得懒惰,并且不想使用最少的代码编写代码

FileUtils.copyFile(src, dest)

从ApacheIoCommons中,或者从Google的Guava库中使用。

因为Java7您可以从Java的标准库中使用

您可以创建包装器方法:

public static void copy(String sourcePath, String destinationPath) throws IOException {
    Files.copy(Paths.get(sourcePath), new FileOutputStream(destinationPath));
}
可通过以下方式使用:

copy("source.txt", "dest.txt");

Java7中,您可以使用
Files.copy()
,非常重要的是:在创建新文件后,不要忘记关闭输出流

OutputStream os = new FileOutputStream(targetFile);
Files.copy(Paths.get(sourceFile), os);
os.close();

有关文件和字符串,请参见,您更愿意使用像FileUtils和StringUtils这样的Utils类。它们有一系列预定义的方法来操作文件和字符串。它们包含在Apache通用包中,您可以将其添加到pom.xml中。此处提供了此答案的更完整(和正确)版本:。感谢大家的帮助。对于文件和字符串,您更愿意使用FileUtils和StringUtils之类的Utils类。它们有一系列预定义的方法来操作文件和字符串。它们包含在Apache通用包中,您可以将其添加到pom中。xmlI是最小代码的爱好者。不知道为什么使用实用程序包是“懒惰的”。我喜欢丝线。