【问题标题】: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 方法。它没有给出目录错误。

【问题讨论】:

标签: 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());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多