简体   繁体   English

JAVA:FileInputStream和FileOutputStream

[英]JAVA: FileInputStream and FileOutputStream

I have this strange thing with input and output streams, whitch I just can't understand. 我对输入和输出流有这个奇怪的事情,我只是无法理解。 I use inputstream to read properties file from resources like this: 我使用inputstream从这样的资源中读取属性文件:

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

It finds my file and reds it succesfully. 它找到我的文件并成功更新它。 I try to write modificated settings like this: 我尝试写这样的修改设置:

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

And I getting strange error from storing: 我收到奇怪的错误:

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

So why path to properties are changed? 那么为什么改变物业的道路呢? How to fix this? 如何解决这个问题? I am using Netbeans on Windows 我在Windows上使用Netbeans

The problem is that getResourceAsStream() is resolving the path you give it relative to the classpath, while new FileOutputStream() creates the file directly in the filesystem. 问题是getResourceAsStream()正在解析相对于类路径的路径,而new FileOutputStream()直接在文件系统中创建文件。 They have different starting points for the path. 他们有不同的起点。

In general you cannot write back to the source location from which a resource was loaded, as it may not exist in the filesystem at all. 通常,您无法回写加载资源的源位置,因为它可能根本不存在于文件系统中。 It may be in a jar file, for instance, and the JVM will not update the jar file. 例如,它可能位于jar文件中,JVM不会更新jar文件。

May be it works 可能是有效的

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();
}

and check the below url 并检查以下网址

getResourceAsStream() vs FileInputStream getResourceAsStream()vs FileInputStream

Please see this question: How can I save a file to the class path 请参阅此问题: 如何将文件保存到类路径

And this answer https://stackoverflow.com/a/4714719/239168 这个答案https://stackoverflow.com/a/4714719/239168

In summary: you can't always trivially save back a file your read from the classpath (eg a file in a jar) 总结:你不能总是简单地保存从类路径读取的文件(例如jar中的文件)

However if it was indeed just a file on the classpath, the above answer has a nice approach 但是,如果它确实只是类路径上的一个文件,那么上面的答案有一个很好的方法

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

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