Saving a newly created .csv file to a specific directory location/ package - Java

536 views Asked by At

Automating a test and need to save a csv to a certain location already wired up for the next step.

if (bulkJobType.equalsIgnoreCase("IP_REMOVAL")) {
            ipFileName = "IP_REMOVAL" + dtf.format(dateTimeNow) + "ip.csv";
            FileWriter fw = new FileWriter(ipFileName);
            try (PrintWriter pw = new PrintWriter(new FileWriter(ipFileName))) {
                pw.write("IP_REMOVAL");
                pw.write(System.getProperty("line.separator"));
                pw.write a few other proprietary attributes
            }

I know 100% that this works as I have several correctly formatted unversioned files, just not in the correct place in the file structure.

File structure:

name
├── build
├── src
│   ├── test
│       └─java (csv creation happens in here btw)
│       └─resources
│          └─*FOLDER I WANT CSV TO SAVE IN *
│            └─IP_REMOVAL.CSV
├── *WHERE CSV IS ACTUALLY SAVING*`

I've tried several other stack overflow threads but can't get this to work. I find it a bit weird I can't just specify a relative path to where I want to save the newly created csv

Any help appreciated

All the other SO posts. This one FileWriter fw = new FileWriter(new File(dir, str));

seemed the most promising but no luck

1

There are 1 answers

2
The IT Dejan On

You can't save to the resource folder in the runtime without specifying full path of the local filesystem.

When you do this

ipFileName = "IP_REMOVAL" + dtf.format(dateTimeNow) + "ip.csv";

it's equivalent of

ipFileName = "<project_root>IP_REMOVAL" + dtf.format(dateTimeNow) + "ip.csv";

If you do try to save to the resource folder, it will be in the target/classes/ and not in the source code resource folder that you're thinking of.

What you can do, as mentioned in the beginning, is giving full path to the resource file like src/main/resources/folder. Also don't forget to create directories and the file before writing to it.