简体   繁体   中英

JAVA Filewriter: Get the path of created File using FileWriter

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?

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

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM