0

我正在与某人一起完成一项任务,我们需要能够加载和保存文件。目前我们这样做:

robot1.getComputer().loadAndCompileProgram(new File("C:\\Projects\\IO\\program1.txt"));

然而,这要求他和我在完全相同的位置有这个程序。我们更愿意将它存储在我们的 eclipse 项目中,并且能够加载文件,而不管 program1 在我们的计算机中的“完整”位置是什么。我们想做这样的事情:

robot1.getComputer().loadAndCompileProgram(new File("/Project D3 1.15/Progs/program1.txt"));

Project D3 1.15 是 Java 项目,完整字符串是 program1 的 Eclipse 中的路径。然而这不起作用。有没有可能做我们想做的事?

4

4 回答 4

0

What you need is this:

String myProjectDir = System.getProperty("user.dir");
robot1.getComputer().loadAndCompileProgram(new File(myProjectDir +"/myFolder/program1.txt"));

The JVM environment variable "user.dir" points to your project directory (for programs that are run from eclipse)

于 2012-05-21T14:45:12.353 回答
0

好吧,您可以利用诸如 的 Java 系统属性user.dir来到达工作区,然后构造路径。

new File(System.getProperty("user.dir") + File.separator + "program1.txt")

如果通过 Eclipse 运行,这将期望文件直接存在于您的工作区中。

这将是一种真正独立于平台的做事方式。

于 2012-05-21T14:38:11.993 回答
0

Try new File("./Progs/program1.txt") or new File("Progs/program1.txt"")

Besides that: if you are having problems with finding out how to locate files under different IDEs, just create simple class with main method like this:

public class ExpMainClass {
    public static void main(final String[] args) throws Exception {
        System.out.println(new File(".").getAbsolutePath());
    }
}

and run it - this should help understanding from where IDE is executing your application.

于 2012-05-21T14:36:08.917 回答
0

There is a difference between the Eclipse project name, and the real path on the computer. It is possible to have a project named Foo whose path is C:\Projects\Bar.

However, it is possible to do this, since when you execute from Eclipse, you are in the current directory.

Just do this

robot1.getComputer().loadAndCompileProgram(new File("Progs/program1.txt"));

or (if you want to specify the project name)

robot1.getComputer().loadAndCompileProgram(new File("../Project D3 1.15/Progs/program1.txt"));
于 2012-05-21T14:37:04.410 回答