Search code examples
javapathfilewriterabsolute-pathfile-location

java.io.FileWriter: Get the path of File created


I have created an CSV file using java.io.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 its 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?


Solution

  • import java.io.File;    
    
    public class Main {
    
        private static String FILE_NAME = "file.csv";
        
        public static void main(String[] args) {
            
            try {
                //create the file using FileWriter
                FileWriter fw = new FileWriter(FILE_NAME);
                //create a File linked to the same file using the name of this one;
                File f = new File(FILE_NAME);
                //Print absolute path
                System.out.println(f.getAbsolutePath());
                
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            
        }
    }