Dylan Wheeler
Dylan Wheeler

Reputation: 7074

Java Copy File Forcefully

I have a method for copying files:

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) {}
}

Is there a way I can override the "Access is denied" error when copying to a directory?

NOTE: I only need this for Windows computers.

Upvotes: 0

Views: 704

Answers (3)

Abir Guecha
Abir Guecha

Reputation: 1

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

Upvotes: 0

dku.rajkumar
dku.rajkumar

Reputation: 18588

perm = new java.io.FilePermission("/tmp/abc.txt", "read"); hope this will answer your question

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

Upvotes: 0

yati sagade
yati sagade

Reputation: 1375

No. If you're on UNIX, running the program as a user with write privileges for the directory will be required. Just curious, why would you want to override filesystem permissions? Why not just use the appropriate permissions?

Upvotes: 3

Related Questions