Search code examples
javafile-iofilewriter

Create folder and print to text file from command


For example you have a command where the second argument is a directory plus file name:

String fileName = "createF dir/text.txt";
String textToFile="apples, oranges";

How can I create "dir/text.txt", a folder called dir, a txtfile and write the contents of textToFile to it?

The issue is it is a command. And it is file name can be changed to another file name. I can't use FileWriter method. It gives no directory error.


Solution

  • If you're using java 7 or above you can try java.nio.file package. Example code:

    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){}