简体   繁体   English

如何使用类路径中的文件?

[英]How do I use the file from classpath?

I need help getting a file from a file to use it.我需要帮助从文件中获取文件才能使用它。 The file is specified in the -cp option when running jar through the console.当通过控制台运行 jar 时,该文件在 -cp 选项中指定。

run the jar using:使用以下命令运行 jar:

java -cp myjar.jar:dir1/dir2/myfile.txt com.company.Main

execution result:执行结果:

Exception in thread "main" java.lang.NullPointerException
  at com.company.Main.main(Main.java:11)

source code:源代码:

package com.company;

import java.io.InputStream;

public class Main {

    public static void main(String[] args) {
        ClassLoader classLoader = Main.class.getClassLoader();
        InputStream resource = classLoader.getResourceAsStream("dir1/dir2/myfile.txt");         
        System.out.println(resource.toString());
    }
}

project tree项目树

-- сom
---- company
------ Main.java

How do I get that file from -cp?如何从 -cp 获取该文件?

Since you specify dir1/dir2/myfile.txt in the getResourceAsStream() call, you want the directory containing dir1 on the classpath, which would be the working directory , ie .由于您在getResourceAsStream()调用中指定了dir1/dir2/myfile.txt ,因此您需要在类路径上包含dir1目录,这将是工作目录,即. :

java -cp myjar.jar:. com.company.Main

The classpath can only specify:类路径只能指定:

  • Directories目录
  • Jar files Jar 文件

No other type of file is supported.不支持其他类型的文件。

It appears that your computer cannot find the file.您的计算机似乎找不到该文件。 Right click on the file and select explorer to see the path or if you are using intellij idea you will see an option to copy the path when you right click on it.右键单击文件并选择资源管理器以查看路径,或者如果您使用的是 intellij idea,当您右键单击它时,您将看到一个复制路径的选项。

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

相关问题 如何使用Java ClassLoader从类路径加载文件? - How do I use the Java ClassLoader to load a file fromthe classpath? 如何在Guava中使用ClassPath :: getAllClasses? - How do I use ClassPath::getAllClasses in Guava? 如何从类路径中提取文件? - How can I extract a file from a classpath? 如何从文件中读取jar列表并将其用作Gradle中的类路径? - How can I READ list of jars from a file and use it as classpath in Gradle? 如何使用类加载器在model.zip文件上获取输入流,其中zip文件包装在classpath中的.jar文件中 - How do I use a classloader to get inputstream on a model.zip file where the zip file is wrapped in a .jar file in classpath 如何将.jar文件添加到Rhino的类路径中? - How do I add a .jar file to Rhino's classpath? 如何在Eclipse插件中获取IJavaProject的类路径作为文件路径? - How do I get the classpath, as file paths, of an IJavaProject in an Eclipse plugin? 如何获取File API来查看我的类路径? - How do I get the File API to look at my classpath? 如何在gradle中的类路径之外指定quartz属性文件? - How do I specify a quartz property file outside of the classpath in gradle? 如何从java检查PATH和CLASSPATH环境变量? - How Do I check PATH and CLASSPATH environment variables from java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM