[英]Program works fine in compiler but not in jar (Java)
I Exported my program into a jar file but when I ran it, it seems as if the .properties file isn't found by the program. 我将程序导出到jar文件中,但是当我运行它时,似乎该程序找不到.properties文件。 I made sure it was in the jar file & it worked fine prior to exporting it. 我确保它在jar文件中,并且在导出之前工作正常。 I read something about using getClass().getResourceAsStream()
instead of FileInputStream
and FileOutputStream
but can't seem to understand how that would help. 我读了一些有关使用getClass().getResourceAsStream()
而不是FileInputStream
和FileOutputStream
但似乎无法理解这会如何帮助。 Any ideas? 有任何想法吗? These are the two methods that use the file. 这是使用文件的两种方法。
private void UpdateData() throws IOException{
FileInputStream in = new FileInputStream("config.properties");
Properties props = new Properties();
props.load(in);
in.close();
FileOutputStream out = new FileOutputStream("config.properties");
props.setProperty("prop1", prop1TextArea.getText().toString());
props.setProperty("prop2", prop2TextArea.getText().toString());
props.setProperty("prop3", prop3TextArea.getText().toString());
props.store(out, null);
out.close();
}
private void setText() throws IOException {
FileInputStream in = new FileInputStream("config.properties");
Properties props = new Properties();
props.load(in);
in.close();
FileOutputStream out = new FileOutputStream("config.properties");
prop1TextArea.setText(props.getProperty("prop1"));
prop2TextArea.setText(props.getProperty("prop2"));
prop3TextArea.setText(props.getProperty("prop3"));
out.close();
}
To access resources in your .jar
file you have to access them as resources not as files. 要访问.jar
文件中的资源,您必须将它们作为资源而不是文件来访问。
The .properties
are not in the filesystem anymore and therefore you cannot access them via FileInputStream
. .properties
不再在文件系统中,因此您无法通过FileInputStream
访问它们。
If you want to save them afterwards you have to create new .properties
on the first start of your program. 如果要在以后保存它们,则必须在程序的第一次启动时创建新的.properties
。 So you have to check first if the file exists (eg via File.exists()
) and either work without the properties from the file or create a new file and use this then. 因此,您必须首先检查文件是否存在(例如,通过File.exists()
),然后在没有文件属性的情况下工作,或者创建一个新文件,然后使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.