简体   繁体   English

写入时出现Java IO错误,但读取时却没有

[英]Java IO Error when writing but not when reading

So the problem is I try to read the configuration file that is packed inside the .jar which works fine but then when it comes to writing to the file the file can not be found yet they are using the same 所以问题是我尝试读取打包在.jar内的配置文件,该文件工作正常,但是当写入该文件时,找不到该文件,但他们使用的是相同的文件

getClass().getResource(Path);

it only seems to work with the input stream. 它似乎只适用于输入流。

Here is all the code of my IO class. 这是我的IO类的所有代码。

package com;

public class IO { 公共类IO {

public boolean CheckStream () {
    String LineRead;

    try {

        InputStream IS = getClass().getResourceAsStream("Config.txt");

        InputStreamReader ISR = new InputStreamReader (IS,Charset.forName("UTf-8"));
        BufferedReader BR = new BufferedReader(ISR);

        if ((LineRead = BR.readLine()) != null) {
            BR.close();
            return true;
        }

        IS.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return false;
}

public void Write (String Path, String [] ThingsToWrite) throws FileNotFoundException {
    OutputStream Out = new FileOutputStream (getClass().getResource(Path).getPath());
    PrintStream PS = new PrintStream (Out);

    for (int i = 0; i < ThingsToWrite.length; i ++) {
        PS.print(ThingsToWrite[i]);
    }

    PS.close();
}

} }

Any Help is greatly appreciated thanks. 非常感谢任何帮助。

You can't just write to a file within a jar file - it's not a file in the regular sense. 您不能只写jar文件中的文件-它不是常规意义上的文件。

While you could unpack the whole jar file, write the new content, then pack it up again, it would be better to redesign so that you don't need to update the jar file. 虽然您可以解压缩整个jar文件,编写新内容,然后再次打包,但最好重新设计,这样就不必更新jar文件。

For example, you might have a regular local file which is used if it's present, but then fall back to reading from the jar file otherwise. 例如,您可能有一个常规的本地文件(如果存在的话),但是如果没有,则回落到从jar文件读取。 Then you only need to write to the local file. 然后,您只需要写入本地文件。

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

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