-1
我有一個方法:文件除了由不完整的(文件)名
public void setup() {
File file = new File(74761_control_*.xml)
//some code
}
其中* - 可變部分。事先並不知道它將如何被稱爲文件。該程序需要加載一個具有相同名稱的xml文件。有沒有一個優雅的方式來使用標準的Java SE API來完成這項工作?
我有一個方法:文件除了由不完整的(文件)名
public void setup() {
File file = new File(74761_control_*.xml)
//some code
}
其中* - 可變部分。事先並不知道它將如何被稱爲文件。該程序需要加載一個具有相同名稱的xml文件。有沒有一個優雅的方式來使用標準的Java SE API來完成這項工作?
的java.nio
包有一些convencience方法來遍歷使用文件名模式目錄:
Path dir = Paths.get("c:\\temp");
Iterator<Path> iterator = Files.newDirectoryStream(dir,
"74761_control_*.xml").iterator();
,迭代器「持有」適合上面的水珠圖案的所有路徑。 其餘的是迭代器/文件處理:
if (!iterator.hasNext()) {
// file not found
} else {
Path path = iterator.next();
// process file, e.g. read all data
Files.readAllBytes(path);
// or open a reader
try (BufferedReader reader = Files.newBufferedReader(path)) {
// process reader
}
if (iterator.hasNext()) {
// more than one file found
}
}
不能保證你的模式不匹配多個文件。所以不,這不起作用。 – isnot2bad
@ isnot2bad我保證這個模式只有一個文件。 – Gleb
是的,你自己保證,但因爲你不能保證世界其他地方,所以沒有直接的java API允許你使用一個模式來構造一個'File'對象,總是作爲一個'File'對象引用一個文件或目錄。但請參閱下面的答案,還有另外一種方法,不需要更復雜的方法來完成您想要的任務。 – isnot2bad