Search code examples
javafilemkdir

How do I add files to my folder? java


My program is creating files and I'm needing to put them in a specific folder. Not sure of the process. Thanks

String path = "C:\\Users\\Blah\\Desktop\\blahblah\\FOLDER";
File bfFolder = new File (path);
bfFolder.mkdir();

for (int a = 0; a < 20; a++) {
    try (DataOutputStream dataO = new DataOutputStream(new FileOutputStream("file" + " a"))) {

Solution

  • You can pass a File to new FileOutputStream(). To create a new File inside the directory you created, pass the parent directory and the filename to the constructor:

    // This will refer to C:\Users\Blah\Desktop\blahblah\FOLDER\name.txt
    File myFile = new File(bfFolder, "name.txt");
    try(FileOutputStream fStream = new FileOutputStream(myFile);
        DataOutputStream data0 = new DataOutputStream(fStream)) {