在Java中获取Mac上文件的路径,但不包括用户名部分。

huangapple go评论79阅读模式
英文:

Path for a file on a Mac without the username in Java

问题

我希望能够在Java程序中通过一些基本的指示打开文本文件
目前我已经可以打开文件的代码如下

```java
Desktop desktop = Desktop.getDesktop();
File file = new File(/* 文件路径,这是我关心的部分。 */);
if (file.exists()) {
    try {
        desktop.open(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这段代码可以正常工作,我目前使用的文件路径是:

"/Users/Box/Documents/text.txt"

我遇到问题的原因是,我想把我的程序发送给朋友,让他试用。我目前的解决方案是添加一个文本字段,用户可以在其中输入用户名,然后文件路径为:

"/Users/" + username + "/Documents/text.txt"(其中username是用户在文本字段中输入的用户名)

除此之外,我还能在哪里存储文件?还有什么其他路径可以使用?有没有一种自动找到用户的方法?我应该将文件存储在根目录下新建的文件夹中吗?


<details>
<summary>英文:</summary>

I want to be able to open a text file with some basic instruction from within a program in Java, 
What I currently have to open the file:

Desktop desktop = Desktop.getDesktop();
File file = new File(/* File Path, this is what I am concerned with. */);
if(file.exists())
try {
desktop.open(file);
} catch (IOException e) {e.printStackTrace();}


This works fine, what I have been using for the path is: 

&quot;/Users/Box/Documents/text.txt&quot;

The reason I have a problem is because I want to send my program to a friend so that he can try it out. The current solution I have is to have a text field that the user can input their username into and then the path is:

&quot;/Users/&quot; + username + &quot;/Documents/text.txt&quot; (username being the username that is inputed into the text field)

Where else could I store the file or what else could I use for a path? Is there a way to find the user automatically? Should I store the file in a folder made in the root?

</details>


# 答案1
**得分**: 1

如果您希望在用户文件夹下使用固定路径,您可以通过以下方式获取用户名:

String username = System.getProperty("user.name");


或者,您可以使用相对于程序位置的路径,例如`Paths.get("").toAbsolutePath()`,参见 https://stackoverflow.com/questions/4871051/getting-the-current-working-directory-in-java

<details>
<summary>英文:</summary>


If you like to use a fixed path under the user folder, you can get the username via

    String username = System.getProperty(&quot;user.name&quot;);

Alternatively you can use a path relative to the location of the program, for example `Paths.get(&quot;&quot;).toAbsolutePath()`, see https://stackoverflow.com/questions/4871051/getting-the-current-working-directory-in-java

</details>



huangapple
  • 本文由 发表于 2020年4月7日 18:36:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/61078070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定