java IO to copy one File to another

前端 未结 6 1114
别那么骄傲
别那么骄傲 2020-11-30 09:48

I have two Java.io.File objects file1 and file2. I want to copy the contents from file1 to file2. Is there an standard way to do this without me having to create a method th

6条回答
  •  我在风中等你
    2020-11-30 10:33

    No. Every long-time Java programmer has their own utility belt that includes such a method. Here's mine.

    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();
        }
    }
    

提交回复
热议问题