按名称在目录中查找特定文件,并将文件保存到本地文件夹

时间:2014-04-09 02:38:38

标签: java properties directory

我想找到一个名为SAVE.properties的文件。我看过他们会回答我的不同问题,但我看不到他们这样做了。

例如,我想检查目录(及其子文件夹)中是否存在SAVE.properties。

我还想知道如何保存.properties文件(然后从此位置读取它)到我的程序运行目录。如果它是从桌面运行的,它应该将.properties文件保存在那里。

1 个答案:

答案 0 :(得分:1)

使用Properties#store(OutputStream, String)可以轻松保存属性,这样您就可以通过OutputStream来定义内容的保存位置。

所以你可以使用......

Properties properties = ...;
//...
try (FileOutputStream os = new FileOutputStream(new File("SAVE.properties"))) {
    properties.store(os, "Save");
} catch (IOException exp) {
    exp.printStackTrace();
}

您还可以使用Properties#load(InputStream)来阅读“属性”文件的内容。

详细了解Basic I/O了解更多详情。

找到File就像使用

一样简单
 File file = new File("SAVE.properties");
 if (file.exists) {...

这将检查当前工作目录中是否存在指定文件。

搜索子目录不太复杂,需要使用一些递归,例如......

public File find(File path) {

    File save = new File(path, "SAVE.properties");
    if (!save.exists()) {
        save = null;
        File[] dirs = path.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return  pathname.isDirectory();
            }
        });
        for (File dir : dirs) {
            save = find(dir);
            if (save != null) {
                break;
            }
        }
    }
    return save;
}

使用find(new File("."))将从当前工作目录开始搜索。请注意,在适当的情况下,这可以搜索整个硬盘。