新的临时目录访问被拒绝

时间:2012-09-28 13:13:21

标签: java file-io

我想创建一个临时目录,之后我应该在其中创建一个文件

我在尝试在临时文件中创建新文件时收到访问被拒绝的消息  所以这是代码:

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

我得到了这个:

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

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

1 个答案:

答案 0 :(得分:3)

您应该在目录中打开一个文件。您正在尝试写入操作系统不允许的目录本身。相反,您应该写入文件。例如,这会使程序在tmpDir:

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

顺便问一下,你为什么不使用File.createTempFile