如何使用相对路径而不是绝对路径? [英] How to use relative path instead of absolute path?

查看:147
本文介绍了如何使用相对路径而不是绝对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我对Java有一个奇怪的问题。

我正在读一个写文件,所以路径对我很重要。我想所有的文件被写入,并从相对路径(即在我的类和Java文件的其余部分的文件夹)中读取。



我写这样的文件:

  FileWriter fw = new FileWriter(outfile,true); 
fw.write(data);
fw.close();



其中outfile与'out.txt'类似(即我们希望输出的文件的名称进去)。

问题是,该文件是在 / home / me / 中创建的,而不是我的其他文件的路径。



我做错了什么?或者我怎样才能得到存储在相​​对目录中的文件?

解决方案

工作目录是你从哪里运行程序的地方你调用java的YourClass,所以当你想写相对于正在执行的类的文件,你将不得不知道当前的目录,并附加从那里的相对路径,例如所以,如果你有一个类test.YourClass,你运行的应用程序从源根即



java test.YourClass



您可以从user.dir系统属性和类包名称中找到类文件所在目录的绝对路径,如下所示: p>

  public class YourClass {
$ b $ public void printPath(){
String path = String.format (%s /%s,System.getProperty(user.dir),this.getClass()。getPackage()。getName()。replace(。,/));
System.out.println(path);

}


So I am having a strange issue with Java.

I'm reading a writing files, so the path is important to me. I would like all files to be written and read from the relative path (i.e in the folder with the rest of my class and java files).

I write files like so:

FileWriter fw = new FileWriter(outfile,true);
fw.write(data);
fw.close();

where outfile is something like 'out.txt' (i.e. the name of the file we want the output to go in).

The problem is, the file is created in /home/me/ instead of the path of my other files.

Am i doing something wrong? Or how can i get the files stored in the relative directory?

解决方案

The working directory is where you run the program from i.e. where you call java YourClass, so when you want to write files relative to the class that's executing you'll have to know the current directory and append the relative path from there e.g.

So if you have a class test.YourClass and you run the application from the source root i.e

java test.YourClass

you can find the absolute path to the directory your class file is in from the the user.dir system property and the classes package name as follows:

public class YourClass {

public void printPath() {
    String path = String.format("%s/%s", System.getProperty("user.dir"), this.getClass().getPackage().getName().replace(".", "/"));
    System.out.println(path);
}

}

这篇关于如何使用相对路径而不是绝对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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