How to get the file absolute path in JAVA project

前端 未结 2 1128
再見小時候
再見小時候 2021-01-21 19:48

Hi I need to read the file by using FileInputStream but I didn\'t get the right path. My file is location at C:\\Users\\tester\\Documents\\Java Project\\Samples\\ProjectOne\\src

2条回答
  •  感动是毒
    2021-01-21 20:16

    You can create file and use getAbsolutePath method:

    File file = new File("TestFile.txt");//full file path URL
    String absolutePath = file.getAbsolutePath();
    

    Here is the simple programme:

    public static void main(String[] args) {
        File f = null;
        String path = "";
        boolean bool = false;
        try {
            // create new files
            f = new File("test.txt");
            // returns true if the file exists
            bool = f.exists();
            // if file exists
            if (bool) {
                // get absolute path
                path = f.getAbsolutePath();
                // prints
                System.out.print("Absolute Pathname " + path);
            }
        } catch (Exception e) {
            // if any error occurs
            e.printStackTrace();
        }
    }
    

提交回复
热议问题