IOException - Access Denied Using FileOutputStream

前端 未结 3 646
孤城傲影
孤城傲影 2020-12-11 19:58

I get the following IOException :

java.io.IOException: Access is denied
 at java.io.WinNTFileSystem.createFileExclusively(Native Method)
 at java.io.File.cre         


        
3条回答
  •  隐瞒了意图╮
    2020-12-11 20:10

    The issue is that these calls step on each other:

      fileToWrite.mkdirs(); //creates a directory e.g. C:\temp\foo\x
      fileToWrite.createNewFile(); //attempts to create a file C:\temp\foo\x
    

    The create operation fails because you just created a directory with the same name than the file you want to create.

    What you want to do instead is:

    fileToWrite.getParentFile().mkdirs()

    And also, the call to createNewFile() is unnecessary.

    Based on your code. The following "unzips" a zip file:

    import java.io.*;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipEntry;
    import java.util.Enumeration;
    
    public class Unzipper {
        public static void main(String[] args)
                throws IOException {
            final File file = new File(args[0]);
            final ZipFile zipFile = new ZipFile(file);
            final byte[] buffer = new byte[2048];
            final File tmpDir = new File(System.getProperty("java.io.tmpdir"), zipFile.getName());
    
            if(!tmpDir.mkdir() && tmpDir.exists()) {
                System.err.println("Cannot create: " + tmpDir);
                System.exit(0);
            }
    
            for(final Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
                final ZipEntry zipEntry = (ZipEntry) entries.nextElement();
                System.out.println("Unzipping: " + zipEntry.getName());
    
                final InputStream is = zipFile.getInputStream(zipEntry);
                final File fileToWrite = new File(tmpDir, zipEntry.getName());
                final File folder = fileToWrite.getParentFile();
                if(!folder.mkdirs() && !folder.exists()) {
                    System.err.println("Cannot create: " + folder);
                    System.exit(0);
                }
    
                if(!zipEntry.isDirectory()) {
                    //No need to use buffered streams since we're doing our own buffering
                    final FileOutputStream fos = new FileOutputStream(fileToWrite);
                    int size;
                    while ((size = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, size);
                    }
                    fos.close();
                    is.close();
                }
            }
            zipFile.close();
        }
    }
    

    Disclaimer: I haven't tested it beyond the very basics.

提交回复
热议问题