JAVA Filewriter: Get the path of created File using FileWriter

BATMAN picture BATMAN · Jul 23, 2017 · Viewed 16.9k times · Source

I have created an CSV file using FILEWRITER and its creating the file in my workspace but I want to display the location (absolute path) of the path where file is created. I know we can use file.getAbsolutePath() if we have created file using FILE but since I have created the CSV file using FILEWRITER I am not sure how to get absolute path of created file. I tried converting it to String and then assigning it to FILE but still not able to get the location of the file. How to get the absolute Path of the file created using FILEWRITER?

Answer

Nathan Gordon picture Nathan Gordon · Jul 23, 2017

Even if you are not creating a new instance of a file writer by passing in a file it is a easy change and will make your issue easy to solve Use this:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        try {
            File file = new File("res/example.csv");
            file.setWritable(true);
            file.setReadable(true);
            FileWriter fw = new FileWriter(file);
            file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}