-2

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Adam Hanek
  • 83
  • 1
  • 6
  • Possible duplicate of [How to create a folder in Java?](https://stackoverflow.com/questions/3024002/how-to-create-a-folder-in-java) – Fang Apr 04 '18 at 07:07
  • Welcome to StackOverflow! I can't get a clue of what you're trying to say. Please add some more information and include your existing code. **For more help take a look at [How to Ask](https://stackoverflow.com/help/asking)** – Hille Apr 04 '18 at 07:07

2 Answers2

1

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){}
RafalS
  • 5,834
  • 1
  • 20
  • 25
1

Try below one

  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());
    }
}
Ramesh
  • 340
  • 1
  • 7
  • 21