Java拷贝文件强有力

时间:2011-11-25 18:06:16

标签: java file directory copy override

我有一种复制文件的方法:

private static void copy(final String source, final String destination) {
    try {
        final File f1 = new File(source);
        final File f2 = new File(destination);
        final InputStream in = new FileInputStream(f1);
        final OutputStream out = new FileOutputStream(f2);
        final byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    } catch (final FileNotFoundException ignored) {
    } catch (final IOException ignored) {}
}

有没有办法在复制到目录时覆盖“访问被拒绝”错误?

注意:我只需要Windows计算机。

3 个答案:

答案 0 :(得分:3)

没有。如果您使用的是UNIX,则需要以具有该目录写权限的用户身份运行该程序。只是好奇,为什么要覆盖文件系统权限?为什么不使用适当的权限?

答案 1 :(得分:0)

perm = new java.io.FilePermission(" /tmp/abc.txt" ;," read"); 希望这会回答你的问题

http://docs.oracle.com/javase/7/docs/technotes/guides/security/permissions.html

答案 2 :(得分:0)

public static void copyFile(File source, File dest) throws IOException {
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;

    try {
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        inputChannel.close();
        outputChannel.close();
    }
}