我有以下方法:
public String readJson(){
String everything = "";
try(BufferedReader br = new BufferedReader(new FileReader("/users/mypc/test/etc/one.json"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
logger.debug("Everything: " + everything);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.debug("line: " + everything);
return everything;
}
这样可以正常工作。我的问题是我不想硬编码文件路径/users/mypc/test/etc/one.json。我尝试通过执行以下操作将其添加到属性文件中:
test.properties:
file1=/users/mypc/test/etc/one.json
PropertiesHelper.java:
public String GET_FILE_ONE = "file1";
private static String one;
public String getJsonFile(){
one = config.getProperty(this.GET_FILE_ONE);
return one;
}
JsonReader.java:
private static PropertiesHelper helper;
final String GET_FILE_ONE = helper.getJsonFile();
public String readJson(){
String everything = "";
try(BufferedReader br = new BufferedReader(new FileReader(GET_FILE_ONE))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
logger.debug("Everything: " + everything);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.debug("line: " + everything);
return everything;
}
我过去做过类似的事情,但这次我得到一个NullPointerException。我一直在盯着这一段时间,看不出有什么不对。我在属性文件中设置文件路径的方式有什么问题,还是有其他我错过的东西?
答案 0 :(得分:0)
Donnacha在上面回答。
通过添加私有静态PropertiesHelper helper = new PropertiesHelper();解决了该问题。到JsonReader.java。见下文:
private static PropertiesHelper helper;
private static PropertiesHelper helper = new PropertiesHelper();
final String GET_FILE_ONE = helper.getJsonFile();
public String readJson(){
String everything = "";
try(BufferedReader br = new BufferedReader(new FileReader(GET_FILE_ONE))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
logger.debug("Everything: " + everything);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.debug("line: " + everything);
return everything;
}