我正在通过执行mvn jetty:run
目标来使用Maven运行Jetty服务器。在我的 Java 代码中,我使用 java.io.File
读取文件,但我现有的代码假设该进程在我的basedir
下的 /war
目录中运行。
使用Maven Jetty插件时如何设置工作目录?
详:这些文件不是直接在baseDirectory
下,而是在子目录下:具体来说,webapp
目录,它被复制到目标文件夹的${project.artifactId}-${project.version}
我想读取文件,而不必在每次定义文件时添加目标路径。
我可以使用读取文件。
File file = new File("target/myProject-myVersion/fileToRead.txt")
我只想做:
File file = new File("fileToRead.txt")
以下是项目结构。(这是典型的Maven Web应用程序结构。
MyDir/
[pom.xml]
src/main/
java/
com.example.mycode/
MyCode.java
webapp/
[fileToRead.txt]
[index.html]
[jsp.jsp]
WEB-INF/
[web.xml]
在pom.xml
中,我有:
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.7.v20160115</version>
<configuration>
<webAppSourceDirectory>${project.basedir}/target/${project.artifactId}-${project.version}</webAppSourceDirectory>
</configuration>
</plugin>
使用 ServletContext.getRealPath(String)
API。
File file = new File(servletContext.getRealPath("/fileToRead.txt"));