重构else-if具有不同扩展名的运算符?

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 变体吗?

谢谢你,
纳扎尔.

jlo*_*rdo 8

您可以使用以下命令替换整个检查扩展名列表:

// 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)

  • 好,但你需要从文件名中提取扩展名 (4认同)