在java项目中如何获取某个文件的路径

在java项目中如何获取某个文件的路径,第1张

File类有两个常用方法可以得到文件路径一个是:getCanonicalPath(),另一个是:getAbsolutePath(),可以通过File类的实例调用这两个方法例如file.getAbsolutePath()其中file是File的实例对象。下面是一个具体例子:

public class PathTest

{

    public static void main(String[] args)

    {

        File file = new File(".\\src\\baidu")

        System.out.println(file.getAbsolutePath())

        try

        {

            System.out.println(file.getCanonicalPath())

        } catch (IOException e)

        {

            e.printStackTrace()

        }

    }

}

getAbsolutePath()和getCanonicalPath()的不同之处在于,getCanonicalPath()得到的是一个规范的路径,而getAbsolutePath()是用构造File对象的路径+当前工作目录。例如在上面的例子中.(点号)代表当前目录。getCanonicalPath()就会把它解析为当前目录但是getAbsolutePath()会把它解析成为目录名字(目录名字是点号)。

下面是上面程序在我电脑上的输出:

G:\xhuoj\konw\.\src\baidu

G:\xhuoj\konw\src\baidu

package utils

import java.io.FileInputStream

import java.io.FileNotFoundException

import java.io.IOException

import java.util.Properties

public class PropertieUtil {

Properties pro = null

public PropertieUtil(){

this.pro = new Properties()

}

public Properties getProperties(){

return this.pro

}

public Properties load(String fileName){

FileInputStream in = null

try {

fileName = String.valueOf(PropertieUtil.class.getResource("/")).replace("file:/", "") + fileName

in = new FileInputStream(fileName)

pro.load(in)

} catch (FileNotFoundException e) {

System.out.println("==================================")

System.out.println(fileName+"配置文件不存在,请联系管理员")

System.out.println("异常信息:"+e)

} catch (IOException e) {

System.out.println("==================================")

System.out.println("读取"+fileName+"配置文件时发生异常,请联系管理员")

System.out.println("异常信息:"+e)

}

return pro

}

public static void main(String[] args) {

FileInputStream in = null

System.out.println(String.valueOf(PropertieUtil.class.getResource("/")).replace("file:/", ""))

String fileName = String.valueOf(PropertieUtil.class.getResource("/")).replace("file:/", "") + "fileconfig.properties"

try {

in = new FileInputStream(fileName)

System.out.println(""+true)

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace()

}

}

}

上面是读取.properties后缀的文件,你想要这种吗?

希望能够帮到你!


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/12012528.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存