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

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

问题描述

以下是我项目的结构:

我需要在 config.properties > MyClass.java 。
我尝试使用相对路径进行如下操作:

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

两者都给出相同的价值。

Both give the same value.

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

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