如何在Java中定义相对路径 [英] How to define a relative path in java

查看:281
本文介绍了如何在Java中定义相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的项目的结构:

我需要阅读MyClass.java中的config.properties. 我尝试通过如下相对路径进行操作:

I need to read config.properties inside MyClass.java. I tried to do so with a relative path as follows :

// Code called from MyClass.java
File f1 = new File("..\\..\\..\\config.properties");  
String path = f1.getPath(); 
prop.load(new FileInputStream(path));

这给了我以下错误:

..\..\..\config.properties (The system cannot find the file specified)

如何在Java中定义相对路径?我正在使用jdk 1.6并在Windows上工作.

How can I define a relative path in Java? I'm using jdk 1.6 and working on windows.

推荐答案

尝试类似的方法

String filePath = new File("").getAbsolutePath();
filePath.concat("path to the property file");

因此,新文件指向创建路径,通常是项目主文件夹.

So your new file points to the path where it is created, usually your project home folder.

如@cmc所说,

    String basePath = new File("").getAbsolutePath();
    System.out.println(basePath);

    String path = new File("src/main/resources/conf.properties")
                                                           .getAbsolutePath();
    System.out.println(path);

两者都赋予相同的值.

这篇关于如何在Java中定义相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆