简体   繁体   English

找不到 Maven 资源

[英]Maven resource not found

I want to include a text file in a maven project.我想在 Maven 项目中包含一个文本文件。 The code itself compiles, but everytime I try to run it, whether in VS Code or at Command Line, I get: java.io.FileNotFoundException: The provided file path /lightdm-forum.txt does not exist.代码本身会编译,但每次我尝试运行它时,无论是在 VS Code 中还是在命令行中,我都会得到: java.io.FileNotFoundException: The provided file path /lightdm-forum.txt does not exist. The file is located at src/main/resources/, which is the default.该文件位于 src/main/resources/,这是默认的。

Code Snippet:代码片段:

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();

        DataStream<Tuple2<String, Integer>> dataStream = env
                .readTextFile("/lightdm-forum.txt")
                .flatMap(new Splitter())
                .keyBy(0)
                .sum(1);

        dataStream.print();

        env.execute("Socket Stream WordCount");
    }

Maven seems to recognize the file and copies it to the classpath root: Maven 似乎识别该文件并将其复制到类路径根目录:

[INFO] --- maven-resources-plugin:3.0.2:resources (default-resources) @ WordCount_Stream ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource

After compiling, the structure in the target folder looks like this:编译后,目标文件夹中的结构如下所示:

.
├── classes
│   ├── com
│   │   └── lmu
│   │       └── WordCount_Stream
│   │           ├── WordCounter$Splitter.class
│   │           └── WordCounter.class
│   └── lightdm-forum.txt

So the file has been copied, but it is not found when I try to run the project.所以文件已经被复制了,但是当我尝试运行项目时没有找到它。 Any ideas?有任何想法吗?

You use /lightdm-forum.txt which is a path as global path.您使用/lightdm-forum.txt作为全局路径的路径。 May you try to use a relative path like path/to/your/subfolder/or/file or ../path/to/upper/folder/and/other/folders .您可以尝试使用相对路径,例如path/to/your/subfolder/or/file../path/to/upper/folder/and/other/folders

Maybe a better solution could be the usage of a classloader like Thread.currentThread().getContextClassLoader().getResource(resourceName) .也许更好的解决方案可能是使用类加载器,如Thread.currentThread().getContextClassLoader().getResource(resourceName) With that you will be able to load files from maven resource package (src/Main/resources by default, Van be also customized in pom.xml)这样你就可以从 maven 资源包中加载文件(默认为 src/Main/resources,Van 也可以在 pom.xml 中自定义)

Hope it helps!希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM