Exception in thread "main" java.io.FileNotFoundException: d: \ aaaa \ a.txt (system can not find the path specified.)

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:
Here Insert Picture Description

Analyze the reasons:

Indeed d:/aaaa/a.txtfile has been created, but a.txtis treated as, instead of a file directory created.
Here Insert Picture Description

Solution:

The d:/aaaaas directory creation, a.txtbe 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:
Here Insert Picture Description

Published 297 original articles · won praise 263 · Views 1.14 million +

Guess you like

Origin blog.csdn.net/xiaojin21cen/article/details/104674910