试图冲洗并关闭所有位置。仍然不会写入文件。更改的文件位置,文件路径仍未写入文件;但是它会创建它。
public void filePatient(HashMap<Integer,Patient> collection, String filename) {
// crating a file
File file = new File (filename+".txt");
try (PrintWriter out = new PrintWriter(new FileWriter(file),true)) {
for(Patient i: collection.values()) {
out.write(i.getName());
//out.write(i.getHealthNumber());
}
out.flush();
out.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答案 0 :(得分:-1)
您的代码按原样工作。
当您使用try-with-resources时,也可以删除关闭。
这是一个完整的示例:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("a", "my name");
map.put("b", "your name");
filePatient(map, "c:\\temp\\test");
}
public static void filePatient(Map<String, String> collection, String filename) {
// crating a file
File file = new File(filename + ".txt");
try (PrintWriter out = new PrintWriter(new FileWriter(file), true)) {
for (String name : collection.values()) {
out.write(name);
}
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}