简体   繁体   中英

Java appending to file with getClass().getResource(“something”).toString() is not workinh?

Working directory in Eclipse looks like this: 在此处输入图片说明

I am trying to append to happyPreview.scm and have to call this method from SpeechPreview.java . I tried:

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(getClass().getResource("previews" + File.separator + "happyPreview.scm").toString(), true)));

I thought this would work since they're all in the same 'bash' package but it doesn't work? Nothing is appending!

class.getResource()-> root是项目文件夹,而不是当前类的类文件夹。

getClass().getResource("/bash/previews/happyPreview.scm")

You can't write to a class resource, only read, and even then, only streaming.

This is because your code will be packaged in a .jar file, that is on the classpath. The deployed .jar file is read-only. Sure, it's not packaged in a .jar file while developing, but it will be when you are done and need to deploy it.

If you want your code to ship with a default/initial resource, and update it, the updated file must be stored elsewhere. When next you try to read it, you first check that other location, and if not found, then you load from resource file.

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