简体   繁体   English

Java命令行程序类路径问题

[英]Java Command Line Program Classpath Problem

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. 所以我在Eclipse中有一个非常大的项目,运行良好并访问文件等。当在Eclipse中时,我访问具有与项目目录的根相关的本地目录名的文件。

So my project is called "Project1" for example and is inside a directory called "MyProjects" so it looks like this: "MyProjects/Project1". 所以我的项目被称为“Project1”,并且位于一个名为“MyProjects”的目录中,所以它看起来像这样:“MyProjects / Project1”。 I want to access a file in the "MyProjects" folder called "hello.text". 我想访问名为“hello.text”的“MyProjects”文件夹中的文件。 So I just do "../hello.text" and it works fine when I do this in Eclipse. 所以我只做“../hello.text”,当我在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. 我遇到的问题是,当我使用命令使用“java Project1”运行程序时,它运行程序正常,但它无法访问该文件,因为从命令行执行程序时它会从“bin”目录中将它们标记出来。 “Project1”目录。 So it messes up the whole program. 所以它弄乱了整个程序。 Is there anyway to change this easily in my Windows environment or Eclise? 无论如何在我的Windows环境或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. 我希望程序从“Project1”目录执行,如果可能的话,所以我不必每次都更改文件位置。

如何提供目录参数,以便您根本不必担心它?

You can use one of ClassLoader class methods 您可以使用ClassLoader类方法之一

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 为了exaple

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

Can't you start your Java program from the bin directory's parent? 你不能从bin目录的父目录启动你的Java程序吗?

eg 例如

Project1> java -classpath bin MyApp

Does this answer for getting classpath from Eclipse help? 这个从Eclipse获取classpath的答案有帮助吗?

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

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