简体   繁体   English

Java + Linux:工作目录是我的主文件夹

[英]Java + Linux: Working Directory is my home folder

A lot of people have the problem that when they start from nautilus a JAR-application, that the CWD (Current Working Directory) is set to their home folder (and not the folder in which the JAR is in). 许多人遇到的问题是,当他们从nautilus启动JAR应用程序时,会将CWD(当前工作目录)设置为他们的主文件夹(而不是JAR所在的文件夹)。 This is a bug in Nautilus, not especially Linux. 这是Nautilus(尤其是Linux)中的错误。

If you know a trick to make it easier to start a Jar correct instead of opening a terminal and manually type there java -jar myJar.jar , please post it below. 如果您知道使启动Jar正确而不是打开终端并手动在其中键入java -jar myJar.jar ,请在下面发布。

Thanks 谢谢


A short code example of the problem: 该问题的简短代码示例:

File f = new File("ASimpleTextFile.txt");
System.out.println(f.getAbsolutePath());

In Windows, this prints: [The Path To The Jar]/ASimpleTextFile.txt 在Windows中,将输出: [The Path To The Jar]/ASimpleTextFile.txt
But in Linux, it prints: /home/[yourName]/ASimpleTextFile.txt 但是在Linux中,它会打印:/ /home/[yourName]/ASimpleTextFile.txt

This is a very bad Idea because of we often use relative path's to configuration files. 这是一个非常糟糕的主意,因为我们经常使用相对路径来配置文件。 This way, they will not be found, because of the file is pointing to the homefolder. 这样,由于文件指向homefolder,因此将找不到它们。

Basically there is no guarantee what so ever about the current working directory. 基本上,不能保证当前的工作目录如何。

What you CAN do, however, is to ask the JVM about the URL where it found the byte code for a given class (which you know where is put) and use that to locate other resources "next" to it. 但是,您可以做的是向JVM询问有关URL的信息,该URL在哪里找到给定类的字节码(您知道将其放在何处),并使用该URL查找“下一个”资源。

See Determine location of a java class loaded by Matlab 请参阅确定由Matlab加载的Java类的位置

I wrote a tiny C++ application which acts a wrapper that first sets the working directory. 我编写了一个微型C ++应用程序,该应用程序充当包装器,该包装器首先设置了工作目录。 The code of the application can be found here on pastebin . 该应用程序的代码可以在pastebin上找到。 Compile this and move to /usr/bin/java-jar-launch . 编译它并移至/usr/bin/java-jar-launch

Then, in Nautilus, browse to one of your JAR files, select and click right on it and then choose for "open with". 然后,在Nautilus中,浏览到您的JAR文件之一,选择并单击右键,然后选择“打开方式”。 Then select custom command and type java-jar-launch . 然后选择自定义命令并输入java-jar-launch Don't forget to check the check box to remember it for the Java JAR type. 不要忘记选中复选框以记住它的Java JAR类型。 Press OK and close. 按确定并关闭。

If you double click a JAR file in Nautilus, it will be opened with my application, which invokes java with the correct working directory. 如果您在Nautilus中双击一个JAR文件,它将用我的应用程序打开,该应用程序将使用正确的工作目录调用java

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

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