【发布时间】:2012-09-20 13:26:49
【问题描述】:
我需要创建临时目录,但是当我尝试在临时目录中创建文件时,总是被拒绝访问。
java.io.FileNotFoundException: C:\tmpDir7504230706415790917 (Access Denied)
这是我的代码:
public static File createTempDir() throws IOException {
File temp = File.createTempFile("tmpDir", "", new File("C:/"));
temp.delete();
temp.mkdir();
return temp;
}
public File createFile(InputStream inputStream, File tmpDir ) {
File file = null;
if (tmpDir.isDirectory()) {
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;
}
我正在开发一个 Web 应用程序,并且正在使用 tomcat。有没有办法在tomcat服务器内存上创建临时文件?我知道这很奇怪,但我不知道……也许有可能。
【问题讨论】:
-
尝试使用 ByteArrayOutputStream 类而不是 FileOutputStream,这样您就可以将数据写入内存中的缓冲区,而无需使用文件。虽然我不懂 Java,所以无法提供更多帮助。
-
@Oscar 在 ByteArrayOutputStream 中写入数据后,我可以将其转换为文件吗?
-
“Tomcat 服务器内存”与您的问题有什么关系?
-
@EJP 我的意思是有一种方法可以使用 tomcat 上传 java.io.File 然后使用它,就像使用 tomcat 临时存储文件并在使用后删除它们一样。非常感谢
-
换句话说,内存与它无关。您正在寻找一种存储临时文件的方法。我建议你修改你的标题和文字。
标签: java tomcat file-io temporary-files