简体   繁体   中英

Absolute path to file outside of project folder with getResourceAsStream()

I want to create jar which will read txt fom jar and then save txt file to user.home folder. When it is runned again, it will read file from user.home.

I read file like this:

if(getClass().getResourceAsStream("/"+System.getProperty("user.home")+"/"+file_name) == null){
            configStream = getClass().getResourceAsStream(file_name);
        } else {
            configStream = getClass().getResourceAsStream(System.getProperty("user.home")+ "/"+file_name);
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(configStream));

And then I write to file like this:

try {
        BufferedWriter out = new BufferedWriter(new FileWriter(System.getProperty("user.home")+ "/" + file_name));
        for (int j = 0; j < y; j++) {
            for (int i = 0; i < x; i++) {
                if (((Block) (listArray.get(i).get(j))).getState() == blockState.blank) {
                    out.write("0");
                } else if (((Block) (listArray.get(i).get(j))).getState() == blockState.solid) {
                    out.write("1");
                } else if (((Block) (listArray.get(i).get(j))).getState() == blockState.player) {
                    out.write("I");
                } else if (((Block) (listArray.get(i).get(j))).getState() == blockState.spikes) {
                    out.write("^");
                } else if (((Block) (listArray.get(i).get(j))).getState() == blockState.water) {
                    out.write("~");
                } else if (((Block) (listArray.get(i).get(j))).getState() == blockState.transparent) {
                    out.write("T");
                }
            }
            out.write("\n");
        }
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

I don't know why, but program never read file from user.home, it always reads one from project folder. Where am I making a mistake? Thanks

You cannot use getResourceAsStream on locations that are not within the JVM classpath. The following snippet works because somewhere within your JVM classpath the file_name exists.

getClass().getResourceAsStream(file_name);

What you are attempting to do here in the next snippet is to use the current class's classloader to load a file that may or may not be part of the JVM classpath.

configStream = getClass().getResourceAsStream(System.getProperty("user.home")+ "/"+file_name);

The relative root node from which this path will be traversed can also not be controller. Use a FileInputStream and load the file from an absolute path like /usr/local/file_name instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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