problem
Learning IO streams, want to change the character persisted to the a.txt file, the code is as follows:
public class Test {
public static void main(String[] args) throws IOException {
File file=new File("d:/aaaa/a.txt");
if(!file.exists()){
file.mkdirs();
}
FileWriter writer=new FileWriter(file,true);
Map paramMap=new HashMap();
paramMap.put("id", 101);
paramMap.put("name", "张三");
paramMap.put("score", "62");
String str=JSONUtils.beanToJson(paramMap);
System.out.println(str);
writer.write(str);
writer.write("\r\n");
writer.close();
}
}
After executing the code, throw an
Exception in thread "main" java.io.FileNotFoundException: d:\aaaa\a.txt (系统找不到指定的路径。)
exception: ,
as the picture shows:
Analyze the reasons:
Indeed d:/aaaa/a.txt
file has been created, but a.txt
is treated as, instead of a file directory created.
Solution:
The d:/aaaa
as directory creation, a.txt
be treated as an empty file to create.
public class Test {
public static void main(String[] args) throws IOException {
File file=new File("d:/aaaa/a.txt");
if (!file.exists()) {
// 1,先得到文件的上级目录,并创建上级目录
file.getParentFile().mkdir();
try {
// 2,再创建文件
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter writer=new FileWriter(file,true);
Map paramMap=new HashMap();
paramMap.put("id", 101);
paramMap.put("name", "张三");
paramMap.put("score", "62");
String str=JSONUtils.beanToJson(paramMap);
System.out.println(str);
writer.write(str);
writer.write("\r\n");
writer.close();
}
}
test
After executing the code, there is no error, look at the results: