我有一个以下形式的树形图:< String, String[] >
我的 String[] 中有一些值为空的值。当使用下面的代码将结果写入文件时,我得到:
java.lang.NullPointerException
我当前写入文件的代码如下,我正在尝试用空字符串替换空值。
new File(outFolder).mkdir();
File dir = new File(outFolder);
//get the file we're writing to
File outFile = new File(dir, "javaoutput.txt");
//create a writer
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFile), "utf-8"))) {
for (Map.Entry<String, String[]> entry : allResults.entrySet()) {
writer.write(entry.getKey() + " "+ Arrays.toString(entry.getValue()).replace(null, ""));
writer.newLine();
}
有什么想法吗?
最佳答案
您的问题是由以下方法调用引起的:replace(null,"");
检查replace()的实现
它采用的第一个参数是一个CharSequence
,它对这个字符序列所做的第一件事是调用toString()
。
这每次都会抛出一个NullPointerException
。
Arrays.toString()
但是会将 null
值替换为 "null"
,因此将您的调用更改为: 替换(“null”,“”);
关于java - 替换 <String, String[]> TreeMap 中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60308046/