Java 创建文件夹并从命令打印到文本文件

Java 创建文件夹并从命令打印到文本文件,java,file-io,filewriter,Java,File Io,Filewriter,例如,您有一个命令,其中第二个参数是目录加文件名: String fileName = "createF dir/text.txt"; String textToFile="apples, oranges"; 我怎样才能创建一个名为dir的文件夹--“dir/text.txt”,一个txt文件,并将textToFile的内容写入其中 问题是这是一个命令。文件名可以更改为另一个文件名。我不能使用FileWriter方法。它没有目录错误。如果您使用的是java 7或更高版本,您可以尝试java.n

例如,您有一个命令,其中第二个参数是目录加文件名:

String fileName = "createF dir/text.txt";
String textToFile="apples, oranges";
我怎样才能创建一个名为dir的文件夹--“dir/text.txt”,一个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());
    }
}

可能重复欢迎使用StackOverflow!我不知道你想说什么。请添加更多信息并包括现有代码。有关更多帮助,请查看