【问题标题】:Create folder and print to text file from command创建文件夹并从命令打印到文本文件
【发布时间】:2018-04-04 07:04:42
【问题描述】:
例如,您有一个命令,其中第二个参数是目录加文件名:
String fileName = "createF dir/text.txt";
String textToFile="apples, oranges";
如何创建"dir/text.txt",一个叫dir的文件夹,一个txtfile,并将textToFile的内容写入其中?
问题是它是一个命令。并且它的文件名可以更改为另一个文件名。我不能使用FileWriter 方法。它没有给出目录错误。
【问题讨论】:
-
-
欢迎来到 StackOverflow!我不知道你想说什么。请添加更多信息并包含您现有的代码。 如需更多帮助,请查看How to Ask
标签:
java
file-io
filewriter
【解决方案1】:
如果您使用的是 java 7 或更高版本,您可以尝试 java.nio.file 包。示例代码:
try {
String fileName = "createF dir/text.txt";
String textToFile="apples, oranges";
String directoryPath = fileName.substring(fileName.indexOf(" ")+1, fileName.lastIndexOf('/'));
String filePath = fileName.substring(fileName.indexOf(" ")+1, fileName.length());
Files.createDirectory(Paths.get(directoryPath));
Files.write(Paths.get(filePath), textToFile.getBytes());
}
catch (IOException e){}
【解决方案2】:
试试下面一个
public static void main(String[] args) throws IOException {
String fileName = "createF dir\\text.txt";
String textToFile="apples, oranges";
String splitter[] = fileName.split(" ");
String actualPath = splitter[1];
File file = new File(actualPath);
if (file.getParentFile().mkdir()) {
file.createNewFile();
new FileOutputStream(actualPath).write(textToFile.getBytes());
} else {
throw new IOException("Failed " + file.getParent());
}
}