Java命令行程序类路径问题
所以我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 ClassLoader 类方法之一
以独立于代码位置的方式定位和访问类路径中的任何资源。例如
You can use one of ClassLoader class methods
to locate and access any resource in the classpath in a way that is independent of the location of the code. For exaple
提供一个目录参数怎么样,这样您就不必担心它了?
How about providing a directory argument so you don't have to worry about it at all ever?
您不能从
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?