Java命令行程序类路径问题

发布于 2024-12-05 00:32:35 字数 444 浏览 0 评论 0原文

所以我在 Eclipse 中有一个相当大的项目,它运行良好并访问文件等。在 Eclipse 中,我访问具有与项目目录根相关的本地目录名称的文件。

例如,我的项目名为“Project1”,位于名为“MyProjects”的目录内,因此它看起来像这样:“MyProjects/Project1”。我想访问“MyProjects”文件夹中名为“hello.text”的文件。所以我只需执行“../hello.text”,当我在 Eclipse 中执行此操作时,效果很好。

我遇到的问题是,当我使用“java Project1”命令运行程序时,它可以正常运行程序,但无法访问该文件,因为当从命令行执行程序时,它会从位于“Project1”目录。所以它搞乱了整个程序。有没有办法在我的 Windows 环境或 Eclise 中轻松更改此设置?我希望我的问题有意义。如果可能的话,我希望程序从“Project1”目录执行,这样我就不必每次都更改文件位置。

so I have a pretty large project in Eclipse which runs fine and accesses files etc. And when in Eclipse I access files with a local directory name in relation to the root of the project directory.

So my project is called "Project1" for example and is inside a directory called "MyProjects" so it looks like this: "MyProjects/Project1". I want to access a file in the "MyProjects" folder called "hello.text". So I just do "../hello.text" and it works fine when I do this in Eclipse.

The problem I have is when I run the program using the command using "java Project1" it runs the program fine but it cannot access that file because when executing programs from the command line it stars them from the "bin" directory which is inside of the "Project1" directory. So it messes up the whole program. Is there anyway to change this easily in my Windows environment or Eclise? I hope my question makes sense. I want the program to execute from "Project1" directory if possible so I don't have to change the file location everytime.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

没有伤那来痛 2024-12-12 00:32:35

您可以使用 ClassLoader 类方法之一

public URL getResource(String name)
or 
public InputStream getResourceAsStream(String name)

以独立于代码位置的方式定位和访问类路径中的任何资源。例如

InputStream myTextFileStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("Project1/Hello.txt") ;

You can use one of ClassLoader class methods

public URL getResource(String name)
or 
public InputStream getResourceAsStream(String name)

to locate and access any resource in the classpath in a way that is independent of the location of the code. For exaple

InputStream myTextFileStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("Project1/Hello.txt") ;
溺孤伤于心 2024-12-12 00:32:35

提供一个目录参数怎么样,这样您就不必担心它了?

How about providing a directory argument so you don't have to worry about it at all ever?

余罪 2024-12-12 00:32:35

您不能从 bin 目录的父目录启动 Java 程序吗?

例如

Project1> java -classpath bin MyApp

是否此答案获取Eclipse 的类路径 有帮助吗?

Can't you start your Java program from the bin directory's parent?

e.g.

Project1> java -classpath bin MyApp

Does this answer for getting classpath from Eclipse help?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文