3

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

尝试在临时文件中创建新文件时收到拒绝访问消息,因此代码如下:

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
4

1 回答 1

2

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

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

顺便说一句,你为什么不使用File.createTempFile

于 2012-09-28T13:16:52.057 回答