Amira
Amira

Reputation: 3270

new temporary directory access denied

i want to create a temporary directory after that i should create a file into it

i'm getting access denied message when trying to create new file in the temporary file so here's the code :

public File createFile(InputStream inputStream,File tmpDir )
{ File file = null;
      try {
            file=new  File(tmpDir.getAbsolutePath());
            // write the inputStream to a FileOutputStream
            OutputStream out = new FileOutputStream(file);

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = inputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            inputStream.close();
            out.flush();
            out.close();

            System.out.println("New file created!");
            } catch (IOException e) {
            System.out.println(e.getMessage());
            } 
      return file;}

/**
 * Create a new temporary directory. Use something like
 * {@link #recursiveDelete(File)} to clean this directory up since it isn't
 * deleted automatically
 * @return  the new directory
 * @throws IOException if there is an error creating the temporary directory
 */
public static File createTempDir() throws IOException
{
    final File sysTempDir = new File(System.getProperty("java.io.tmpdir"));
    File newTempDir;
    final int maxAttempts = 9;
    int attemptCount = 0;
    do
    {
        attemptCount++;
        if(attemptCount > maxAttempts)
        {
            throw new IOException(
                    "The highly improbable has occurred! Failed to " +
                    "create a unique temporary directory after " +
                    maxAttempts + " attempts.");
        }
        String dirName = UUID.randomUUID().toString();
        newTempDir = new File(sysTempDir, dirName);
    } while(newTempDir.exists());

    if(newTempDir.mkdirs())
    {
        return newTempDir;
    }
    else
    {
        throw new IOException(
                "Failed to create temp dir named " +
                newTempDir.getAbsolutePath());
    }
}

i'm getting this :

C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\e18a5cdb-a975-46e7-874c-4ea21e2fb383 (Access denied)

 e18a5cdb-a975-46e7-874c-4ea21e2fb383

Upvotes: 3

Views: 7184

Answers (1)

Joni
Joni

Reputation: 111349

You should open a file within the directory. You are trying to write to the directory itself, which the operating system does not allow. Instead you should write to a file. For example, this would make the program create MyFile.txt inside tmpDir:

file=new  File(tmpDir, "MyFile.txt");

By the way, why are you not using File.createTempFile?

Upvotes: 3

Related Questions