Java 为什么不是';我的方法是使用哈希映射将文件写入txt文件
我不完全清楚为什么我的方法不起作用。我使用的是write-a-file方法,它基本上使用HashMap来写入外部文本文件。下面是哪一个Java 为什么不是';我的方法是使用哈希映射将文件写入txt文件,java,hashmap,bluej,Java,Hashmap,Bluej,我不完全清楚为什么我的方法不起作用。我使用的是write-a-file方法,它基本上使用HashMap来写入外部文本文件。下面是哪一个 public void writeAMap(HashMap<String, String> map, String filename) { if(map != null) { try (FileWriter writer = new FileWriter(filename, true)) {
public void writeAMap(HashMap<String, String> map, String filename)
{
if(map != null) {
try (FileWriter writer = new FileWriter(filename, true)) {
for(String key : map.keySet()) {
String value = map.get(key);
if(value == null) {
System.out.println("Warning: Null response for " +
key + " in writeAMap. Using a default.");
value = "I don't know what you mean?";
}
writer.write(key.trim());
writer.write('\n');
writer.write(value.trim());
writer.write('\n');
}
writer.close();
}
catch(IOException e) {
System.out.println("Problem writing file: " + filename +
" in writeAMap");
}
}
else {
System.out.println("Null map passed to writeAMap.");
}
}
public void writemap(HashMap映射,字符串文件名)
{
if(map!=null){
try(FileWriter=newfilewriter(文件名,true)){
for(字符串键:map.keySet()){
字符串值=map.get(键);
如果(值==null){
System.out.println(“警告:对于”+
使用默认值在WriteMap中输入+);
value=“我不知道你的意思?”;
}
writer.write(key.trim());
writer.write('\n');
writer.write(value.trim());
writer.write('\n');
}
writer.close();
}
捕获(IOE异常){
System.out.println(“写入文件时出现问题:”+文件名+
“书面协议”);
}
}
否则{
System.out.println(“传递给WriteMap的空映射”);
}
}
然后在另一个类中使用下面的方法调用上面的方法
public void mapWrite(HashMap<String, String>map)
{
help.writeAMap(map, "responses.txt");
}
publicmapwrite(HashMapmap)
{
help.writemap(map,“responses.txt”);
}
然后我编写了下面的方法,以便在主类中调用上面的方法
if (input.contains("write")) {
HashMap<String, String> key = new HashMap<String, String>();
instruct.mapWrite(key);
}
if(input.contains(“write”)){
HashMap key=newhashmap();
指令.mapWrite(键);
}
这可以很好地编译,并且不会出现错误,但它实际上并没有写入外部txt文件。任何关于找出原因的帮助都是非常好的。要更快地得到答案和更详细的答案,请不要调用
writer.close()代码>在try块中。它应该在finally
块中完成,或者因为您使用的是try with resources,您可以完全跳过它。在映射中放入一些内容,可能会工作…您的writemap(HashMap map,String filename)
方法对我来说很好。它会写入外部txt文件吗?