JAVA:FileInputStream 和 FileOutputStream

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10492698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:18:15  来源:igfitidea点击:

JAVA: FileInputStream and FileOutputStream

javafileinputstreamfileoutputstream

提问by gedO

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

采纳答案by user1357722

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() 与 FileInputStream

回答by Jim Garrison

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. They have different starting points for the path.

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

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 文件。

回答by Eran Medan

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 (e.g. a file in a jar)

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

However if it was indeed just a file on the classpath, the above answer has a nice approach

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