访问tomcat目录结构之外的文件

问题描述 投票:0回答:0

我的文件结构不受我的控制。我需要从我的

ServletContextListener
中访问一个文件,该文件位于 tomcat 目录之外。

这是我的代码:

// access a random file to get full path
URL basePathURL = MyContextListener.class.getResource("/somereference.txt");
String path = URLDecoder.decode(basePathURL.getPath(), "UTF-8");

// get relevant part of the path
String tomcatServerDir = path.substring(0, path.indexOf("server"));

// get the parent
Path myRequiredFileDirPath = Paths.get(tomcatServerDir).getParent();

// form path to required file
String confPath = credentialsFileDirPath.toString() + "/fileToAccess.txt";
File myFile = new File(confPath);

// code to read the file here

这会出现以下错误:

java.nio.file.InvalidPathException: Illegal char <:> at index 2: /C:/MyApp/
at java.base/sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
at java.base/sun.nio.fs.WindowsPath.parse(WindowsPath.java:92)
at java.base/sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:229)
at java.base/java.nio.file.Path.of(Path.java:147)
at java.base/java.nio.file.Paths.get(Paths.java:69)

目录结构是这样的:

somereference.txt
的路径:C:\MyApp\server omcat\webapps\mywebapp\WEB-IN
java file
© www.soinside.com 2019 - 2024. All rights reserved.