在Java中更改当前工作目录? [英] Changing the current working directory in Java?

查看:800
本文介绍了在Java中更改当前工作目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java程序中更改当前工作目录?我能找到的关于这个问题的一切声称你根本做不到,但我不相信那是真的。

How can I change the current working directory from within a Java program? Everything I've been able to find about the issue claims that you simply can't do it, but I can't believe that that's really the case.

我有一段代码,它使用来自通常启动的目录的硬编码相对文件路径打开文件,我只是希望能够在不同的Java程序中使用该代码,而无需在特定的Java程序中启动它目录。看起来你应该只能调用 System.setProperty(user.dir,/ path / to / dir),但据我所知out,调用该行只是默默地失败并且什么也不做。

I have a piece of code that opens a file using a hard-coded relative file path from the directory it's normally started in, and I just want to be able to use that code from within a different Java program without having to start it from within a particular directory. It seems like you should just be able to call System.setProperty( "user.dir", "/path/to/dir" ), but as far as I can figure out, calling that line just silently fails and does nothing.

我会理解如果Java不允许你这样做,如果它不是因为它允许你获取当前的工作目录,甚至允许你使用相对文件路径打开文件....

I would understand if Java didn't allow you to do this, if it weren't for the fact that it allows you to get the current working directory, and even allows you to open files using relative file paths....

推荐答案

在纯Java中没有可靠的方法。通过 System.setProperty() java -Duser.dir设置 user.dir 属性= ... 确实会影响文件的后续创作,但不会影响 FileOutputStreams

There is no reliable way to do this in pure Java. Setting the user.dir property via System.setProperty() or java -Duser.dir=... does seem to affect subsequent creations of Files, but not e.g. FileOutputStreams.

File(String parent,String child) 构造函数可以帮助您与文件路径分开构建目录路径,从而更容易交换。

The File(String parent, String child) constructor can help if you build up your directory path separately from your file path, allowing easier swapping.

另一种方法是设置一个脚本从不同的目录运行Java,或使用JNI本机代码如下所示

An alternative is to set up a script to run Java from a different directory, or use JNI native code as suggested below.

相关的Sun bug 于2008年关闭,因为无法修复。

The relevant Sun bug was closed in 2008 as "will not fix".

这篇关于在Java中更改当前工作目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆