为了在我正在处理的应用程序中提供双语支持,我们正在使用Spring消息传递,该消息传递使用两个文件ApplicationResources.properties和ApplicationResources_fr.properties。 这很好。
现在,我尝试通过使其更具动态性来对此进行扩展。 该应用程序将从数据库中读取键值对并将其插入,这给了我以下错误:
java.io.FileNotFoundException: \ApplicationResources.properties (Access is denied)
我能够检查键值对,因此我知道我使用的路径是正确的。 我还通过右键单击并访问系统上的实际文件来检查Eclipse属性中的文件,它们不是只读的。 我不相信它们是加密的,因为我能够使用notepad ++打开和查看它们。
这是我的测试代码,显示我可以查看它们
Properties test_prop = null;
InputStream is = null;
try {
test_prop = new Properties();
is = this.getClass().getResourceAsStream(en_path);
test_prop.load(is);
Set keys = test_prop.keySet();
boolean key_found = false;
for(Object k:keys) {
String key = (String)k;
if(key.equals("f12345"))
{
key_found=true;
break;
}
}
System.out.println("Language Properties Test in DAO:" + (key_found? "Key Found" : "Key not found"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这是我尝试写入文件并得到错误的地方:
ResultSet rs = null;
try (
Connection connection = jdbcTemplate.getDataSource().getConnection();
CallableStatement callableStatement = connection.prepareCall(test_prod_cur);
)
{
callableStatement.registerOutParameter(1, OracleTypes.CURSOR);
callableStatement.executeUpdate();
rs = (ResultSet) callableStatement.getObject(1);
while (rs.next())
{
String thead = rs.getString(1);
//System.out.println(thead + " " + rs.getString(2) + " " + rs.getString(3));
en_prop.setProperty(keyheader+thead, rs.getString(2));
fr_prop.setProperty(keyheader+thead, rs.getString(3));
}
}
catch (SQLException e)
{
System.out.println("SQLException - bilingual values - CLUDAOImpl");
System.out.println(e.getMessage());
}
//add to properties files
//*
try (OutputStream en_os = new FileOutputStream(en_path);)
{
en_prop.store(en_os, null);
} catch (IOException e) {
e.printStackTrace();
}
try(OutputStream fr_os = new FileOutputStream(en_path);)
{
fr_prop.store(fr_os, null);
} catch (IOException e) {
e.printStackTrace();
}
因此,数据库查询成功,并使用注释掉的system.out.println进行了测试。 以下几行最终引发错误:
en_prop.store(en_os, null);
fr_prop.store(fr_os, null);
更新:我对java.util.Properties进行了搜索,这使我找到了关于它的javadocs,并且哇,这简化了很多事情。 现在,我可以获取属性值或检查键是否存在于6行代码中(不计算try catch)。
Properties prop = null;
InputStream is = null;
this.prop = new Properties();
is = this.getClass().getResourceAsStream(path);
prop.load(is);
this.prop.getProperty("key name"); //returns value of key, or null
this.prop.containsKey("key name"); //returns true if key exists
Update2:使用java.util.Properties时遇到了一个问题,那就是您丢失了原始文件的所有格式,因此空白,注释和排序都丢失了。 在另一个答案中,有人建议使用Apache的Commons Configuration API。 我计划尝试一下。