从命令创建文件夹并打印到文本文件
Create folder and print to text file from command
例如你有一个命令,其中第二个参数是一个目录加上文件名:
String fileName = "createF dir/text.txt";
String textToFile="apples, oranges";
如何创建 "dir/text.txt",一个名为 dir 的文件夹,一个 txt 文件并将 textToFile 的内容写入其中?
问题是它是一个命令。而且它的文件名可以更改为另一个文件名。我不能使用 FileWriter
方法。它没有给出目录错误。
如果您使用的是 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){}
试试下面一个
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());
}
}
例如你有一个命令,其中第二个参数是一个目录加上文件名:
String fileName = "createF dir/text.txt";
String textToFile="apples, oranges";
如何创建 "dir/text.txt",一个名为 dir 的文件夹,一个 txt 文件并将 textToFile 的内容写入其中?
问题是它是一个命令。而且它的文件名可以更改为另一个文件名。我不能使用 FileWriter
方法。它没有给出目录错误。
如果您使用的是 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){}
试试下面一个
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());
}
}