在java中设置没有硬编码的文件位置

时间:2012-10-04 11:11:32

标签: java file

有没有办法可以使用某些功能来动态设置文件的位置(目录)?

每次我使用硬编码这样的文件位置

    String folder = "/Users/...../Desktop/sample";
    File dir = new File(folder);
    File[] files = dir.listFiles();

有什么方法可以避免硬编码吗?我正在使用的位置不是我当前的目录。

在这方面的建议或帮助表示赞赏。 :)

3 个答案:

答案 0 :(得分:3)

我认为一些相当简单的方法是可行的,但可能不完全是你想要的:

从类路径

导航
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL url = cl.getResource("relative/path/from/classpath");

String path = getClass().getClassLoader().getResource(".").getPath();

使用包含路径条目的属性文件

Properties properties = new Properties();
properties.load(new FileInputStream("filename.properties"));
properties.getProperty("PATH")

在您的属性文件中,您将拥有类似

的行
PATH = the/absolute/path

使用环境变量

System.getenv("THE_PATH_ENV")

将路径存储在环境变量中的位置(如果适用于您的操作系统)。


将路径作为参数 好吧,那个很简单......只需访问main ...中的字符串数组。

public static void main(String[] args){
    String path = args[0]; //Or at whatever position it is in your parameter list
    ..

或者我可以认为可以使用Java文件系统命令手动遍历目录结构并在其中搜索某些内容。但是我不建议这样做,因为这不是他们的目的。如果可以的话,我想我会回到某些第三方API。

答案 1 :(得分:0)

How can I get relative path of the folders in my android project?

在项目层次结构中放置一个文件夹,获取项目的相对路径,附加/硬编码文件夹名称和文件名。您最后只会硬编码文件名或最后一个文件夹名称。

答案 2 :(得分:0)

首先,您可以创建一个存储路径的属性文件(您可以运行一次,然后在程序中使用该文件):

/* Create/save properties once */

Properties prop = new Properties();

prop.setProperty("filePath", "/myPath/");

FileOutputStream fos = new FileOutputStream("sampleprops.xml");
prop.storeToXML(fos, "File configuration");
fos.close();

其次,您可以在代码中加载所需的属性:

Properties prop = new Properties();
FileInputStream fis = new FileInputStream("sampleprops.xml");
prop.loadFromXML(fis);

File dir = new File(prop.getProperty("filePath"));
File[] files = dir.listFiles();

您必须确保您可以访问sampleprops.xml文件(应该位于应用程序的类路径中)。这样,您可以从外部配置文件中配置要使用的路径。