6

我对输入和输出流有这个奇怪的东西,我就是无法理解。我使用 inputstream 从资源中读取属性文件,如下所示:

Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream( "/resources/SQL.properties" );
rop.load(in);
return prop;

它找到了我的文件并成功地将其变红。我尝试编写修改后的设置,如下所示:

prop.store(new FileOutputStream( "/resources/SQL.properties" ), null);

我从存储中得到奇怪的错误:

java.io.FileNotFoundException: \resources\SQL.properties (The system cannot find the path specified)

那么为什么改变属性的路径呢?如何解决这个问题?我在 Windows 上使用 Netbeans

4

3 回答 3

6

问题是getResourceAsStream()解决了你给它的相对于类路径的路径,同时new FileOutputStream()直接在文件系统中创建文件。他们有不同的路径起点。

通常,您不能写回加载资源的源位置,因为它可能根本不存在于文件系统中。例如,它可能在 jar 文件中,而 JVM 不会更新 jar 文件。

于 2012-05-08T04:51:19.067 回答
3

可能有效

try
{
java.net.URL url = this.getClass().getResource("/resources/SQL.properties");

java.io.FileInputStream pin = new java.io.FileInputStream(url.getFile());

java.util.Properties props = new java.util.Properties();

props.load(pin);
}
catch(Exception ex)
{
ex.printStackTrace();
}

并检查以下网址

getResourceAsStream() 与 FileInputStream

于 2012-05-08T05:04:07.630 回答
1

请看这个问题:如何将文件保存到类路径

而这个答案https://stackoverflow.com/a/4714719/239168

总而言之:您不能总是轻松地保存从类路径中读取的文件(例如 jar 中的文件)

但是,如果它确实只是类路径上的一个文件,那么上面的答案有一个很好的方法

于 2012-05-08T05:12:14.587 回答