Search code examples
javafilewriter

Ad-hoc directory creation


In the code below ,I am writing a file named employee_status_downloader_unixtimestamp.csv in an already created directory on RHEL server as shown in this line of code below:

FileWriter fw = new FileWriter("/srv/file_users/JACK/employee_status_downloader_"+unixTimestamp+".csv");

So, I manually created a folder named JACK and then specified the above path so that the files related to the userName JACK are inside JACK folder.

Since the userName can be different and I am already getting the userName in my method sendMessage as shown below from this line of code String userName = parts[1].trim();, I am wondering if I could make use of this to create a directory based on the userName?

So, I am not using System.getProperty("user.name"); here since I am already getting userName in my method above which I believe is enough for creating an ad-hoc directory.

After looking online , I found that people are suggesting here(Bozho's answer) to do something like this :

File fl = new File("/path/directory").mkdirs(); where directory is the name of the directory I want to create/exist. But since I am using FileWriter above, I am wondering how should I go about using both so that I could also create a directory if it doesn't exist and then write a file in the directory.

public void sendMessage(String msg) throws DaoException {

        String[] parts = msg.split("#");
        String requestID = parts[0].trim();
        String userName = parts[1].trim();
        String applicationName = parts[2].trim();

        logger.info("Request ID " + requestID);
        logger.info("User Name " + userName);
        logger.info("Application Name " + applicationName);



        try {


            FileWriter fw = new FileWriter("/srv/file_users/JACK/employee_status_downloader_" + unixTimestamp + ".csv");

            CSVWriter writer = new CSVWriter(fw);

            writer.writeAll(rsDemo, true);
            writer.close();
            fw.close();


        } catch (Throwable th) {
            throw new DaoException(th.getMessage(), th);
        } finally {


        }



    }
    long unixTimestamp = Instant.now().getEpochSecond();

Solution

  • If you want to make sure the folder exists, change code to:

    File dir = new File("/srv/file_users/", userName);
    dir.mkdirs();
    FileWriter fw = new FileWriter(new File(dir, "/employee_status_downloader_" + unixTimestamp + ".csv"));
    

    Better yet, use the newer NIO methods and use try-with-resources to ensure file is closed correctly.

    Path dir = Paths.get("/srv/file_users", userName);
    Files.createDirectories(dir);
    
    Path file = dir.resolve("employee_status_downloader_" + unixTimestamp + ".csv");
    try (CSVWriter writer = new CSVWriter(Files.newBufferedWriter(file))) {
        writer.writeAll(rsDemo, true);
    }