我在 Windows 上的 Tomcat 7.0.42 上有这个 Web 应用程序,它被指示复制本地映射网络目录中的文件,例如 N:\some\directory\file.txt
,但它无法这样做。
为了定义输出文件,我使用了 URI 语法 file:///n:/some/directory/file.txt
,但是 Files.copy
和 FileUtils.copyFile
抛出一个 IOException
以及一些不太有用的错误消息:
URI desturi = new URI(srcpath);
File dest = new File(desturi);
Files.copy(source.toPath(), dest.toPath());
// error message: "c:\local\dir\file.txt -> n:\some\directory\file.txt"
FileUtils.copyFile(source, dest);
// error message: "Destination 'N:\some\directory' directory cannot be created"
一些附加信息:
- 当然,我可以在那个目录上读写
- 可执行文件 .jar 可以毫无问题地复制文件
- 如果目的地在本地驱动器中,一切都很好
- 我认为安全管理器没有加载,但我该如何检查呢?
- Tomcat 以我用来登录的同一用户启动(例如,
user.name
与USERNAME
环境变量相同)
我没有想法......
更新 堆栈跟踪的片段。对于 Files.copy
:
java.nio.file.NoSuchFileException: c:\local\dir\file.txt -> n:\some\directory\file.txt
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileCopy.copy(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.copy(Unknown Source)
at java.nio.file.Files.copy(Unknown Source)
at it.augea.print.server.MyClass.copyFileToPath(MyClass.java:886)
at it.augea.print.server.MyServlet.doPost(MyServlet.java:126)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
对于FileUtils.copyFile
:
java.io.IOException: Destination 'N:\some\directory' directory cannot be created
at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:1015)
at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:968)
at it.augea.print.server.MyClass.copyFileToPath(MyClass.java:886)
at it.augea.print.server.MyServlet.doPost(MyServlet.java:126)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
顺便说一句,Apache Commons.io 是 v2.2。查看源代码,这些是涉及的行:
File parentFile = destFile.getParentFile();
if (parentFile != null)
if (!parentFile.mkdirs() && !parentFile.isDirectory())
throw new IOException("Destination '" + parentFile + "' directory cannot be created");
最佳答案
当 Tomcat(或任何其他程序)作为 Windows 服务运行时,它在服务帐户下运行,而这些帐户默认情况下无法访问映射的驱动器(或者如果内存正确地为我提供任何网络路径)。 Tomcat 看不到 N: 驱动器,因此任何写入它的尝试都会失败。
有几种可能的解决方案。我的建议是为 Tomcat 创建一个域帐户,使其在具有最低必要权限的情况下运行,以便 a) 在其运行的机器上作为服务运行,以及 b) 在网络上需要的地方写入。最后,使用 UNC 路径//machinename/sharename/path/in/share 而不是映射的驱动器,你应该可以开始了。
关于java - Tomcat Web 应用程序无法在网络上写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19657041/