JAVA Filewriter: get path to generated file using FileWriter

I created a CSV file using FILEWRITER and creating a file in my workspace, but I want to display the location (absolute path) of the path where the file is created. I know we can use file.getAbsolutePath () if we created the file using FILE, but since I created the CSV file using FILEWRITER, I'm not sure how to get the absolute path to the generated file. I tried converting it to String and then assigning it to FILE but still couldn't get the file location. How do I get the absolute Path of a file created with FILEWRITER?

+3


source to share


2 answers


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();
    } 

}

      



+3


source


Even if you are not creating a new instance of the file writer by passing it to a file, this is a simple change and will make your problem simpler 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();
        }
    }
}

      

+3


source







All Articles