naz*_*art 2 java refactoring if-statement
我想知道我们如何更好地使用else-if运算符来反映这部分代码.何时执行ifuals检查不同的扩展?
码:
private void findFiles(String path) {
try {
File root = new File(path);
File[] list = root.listFiles();
for (File currentFile : list) {
if (currentFile.isDirectory()) {
findFiles(currentFile.getAbsolutePath());
} else {
if (currentFile.getName().toLowerCase().endsWith((".txt"))) {
queue.put(currentFile);
} else if (currentFile.getName().toLowerCase()
.endsWith((".pdf"))) {
queue.put(currentFile);
} else if (currentFile.getName().toLowerCase()
.endsWith((".doc"))) {
queue.put(currentFile);
} else if (currentFile.getName().toLowerCase()
.endsWith((".docx"))) {
queue.put(currentFile);
} else if (currentFile.getName().toLowerCase()
.endsWith((".html"))) {
queue.put(currentFile);
} else if (currentFile.getName().toLowerCase()
.endsWith((".htm"))) {
queue.put(currentFile);
} else if (currentFile.getName().toLowerCase()
.endsWith((".xml"))) {
queue.put(currentFile);
} else if (currentFile.getName().toLowerCase()
.endsWith((".djvu"))) {
queue.put(currentFile);
} else if (currentFile.getName().toLowerCase()
.endsWith((".djv"))) {
queue.put(currentFile);
} else if (currentFile.getName().toLowerCase()
.endsWith((".rar"))) {
queue.put(currentFile);
} else if (currentFile.getName().toLowerCase()
.endsWith((".rtf"))) {
queue.put(currentFile);
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题:
extentions
变体吗?谢谢你,
纳扎尔.
您可以使用以下命令替换整个检查扩展名列表:
// outside the loop (or even method):
Set<String> extensions = new HashSet<>(Arrays.asList(".txt", ".pdf", ".doc",
".docx", ".html", ".htm", ".xml", ".djvu", ".rar", ".rtf"));
// in the loop:
String fileName = currentFile.getName().toLowerCase();
if (extensions.contains(fileName.substring(fileName.lastIndexOf(".")))) {
queue.put(currentFile);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
348 次 |
| 最近记录: |