JAVA Filewriter:使用 FileWriter 获取创建文件的路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45261068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:36:29  来源:igfitidea点击:

JAVA Filewriter: Get the path of created File using FileWriter

javapathfilewriterabsolute-pathfile-location

提问by BATMAN

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?

我已经使用 FILEWRITER 创建了一个 CSV 文件,并在我的工作区中创建了该文件,但我想显示创建文件的路径的位置(绝对路径)。我知道如果我们使用 FILE 创建文件,我们可以使用 file.getAbsolutePath() 但由于我使用 FILEWRITER 创建了 CSV 文件,我不确定如何获取创建文件的绝对路径。我尝试将其转换为字符串,然后将其分配给 FILE,但仍然无法获取文件的位置。如何获取使用 FILEWRITER 创建的文件的绝对路径?

采纳答案by Ferdinando D'avino

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

}

回答by Nathan Gordon

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