[英]Locate a specific file in a directory by name plus saving a file to the local folder
我想找到一個名為SAVE.properties的文件。 我看了看似乎他們會回答我的不同問題,但我看不到他們會回答。
例如,我要檢查目錄(及其子文件夾)中是否存在SAVE.properties。
我還想知道如何將.properties文件保存(然后從該位置讀取它)到運行程序的目錄中。 如果從桌面運行,則應在其中保存.properties文件。
保存屬性可以通過使用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)
讀取“屬性”文件的內容。
詳細了解基本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("."))
將開始從當前工作目錄搜索。 請注意,在適當的情況下,這可能會搜索整個硬盤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.