命令行创建目录与文本文件并写入内容的技术实现问询
Got it, let's break down how to fix this issue. The core problem here is that FileWriter throws an error when the parent directory of your target file doesn't exist—so we need to create the directory structure first before trying to write the file. Here are two solid approaches that handle dynamic file paths smoothly:
Approach 1: Using Traditional File Class
This method works for all Java versions and gives you explicit control over directory creation:
String fileName = "createF dir/text.txt"; // Extract the actual file path from the command (assuming format is "createF <path>") String filePath = fileName.split(" ", 2)[1]; String textToFile = "apples, oranges"; File targetFile = new File(filePath); // Get the parent directory of the target file File parentDir = targetFile.getParentFile(); // Create the full directory structure (including nested folders) if (parentDir != null && !parentDir.exists()) { // Use mkdirs() instead of mkdir() to handle multi-level directories boolean dirCreated = parentDir.mkdirs(); if (!dirCreated) { throw new IOException("Failed to create directory: " + parentDir.getAbsolutePath()); } } // Now safely write content to the file try (FileWriter writer = new FileWriter(targetFile)) { writer.write(textToFile); } catch (IOException e) { e.printStackTrace(); }
Key Details:
getParentFile()grabs the folder containing your target file (e.g.,dirfordir/text.txt).mkdirs()creates all missing parent directories (unlikemkdir()which only makes a single folder level). This is critical for dynamic paths with nested folders likea/b/c/file.txt.- The try-with-resources block ensures the
FileWriteris closed automatically, preventing resource leaks.
Approach 2: Using Java NIO Files Class (Java 7+)
This is a more modern, concise way to handle both directory creation and file writing in one go:
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.charset.StandardCharsets; import java.io.IOException; String fileName = "createF dir/text.txt"; String filePath = fileName.split(" ", 2)[1]; String textToFile = "apples, oranges"; Path targetPath = Paths.get(filePath); // Create parent directories (does nothing if they already exist) Files.createDirectories(targetPath.getParent()); // Write content to the file (overwrites existing files; use StandardOpenOption.APPEND to add content) try { Files.write(targetPath, textToFile.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); }
Key Details:
Files.createDirectories()handles all nested directory creation automatically, no extra existence checks needed.Files.write()simplifies content writing—you can specify UTF-8 explicitly to avoid encoding issues, and it manages stream cleanup internally.
Why Your Original Method Failed
When you use FileWriter directly on a path with non-existent directories, it throws a java.io.IOException: No such file or directory because it can't create the file without its parent folder existing first. By building the directory structure upfront, you eliminate this error entirely.
内容的提问来源于stack exchange,提问作者Adam Hanek

