簡體   English   中英

Java - String.contains()表現得很奇怪

[英]Java - String.contains() behaves oddly

這段代碼在我的開發機器上運行正常(使用Netbeans IDE安裝在VirtualBox jre 8上的Windows 7),但在另一台機器上(Windows 7 jre 8)總是返回true。 它應該只找到名為“town_house.html”的文件,而不是總是為文件夾中的每個文件返回true。從提示中運行jar文件我沒有任何異常。 也許這只是一個微不足道的錯誤,我通常用C / C ++編程......任何想法?

for(File f : files)
        {
            if(f.toString().contains("_") && 
               f.toString().contains(".html")){
                System.out.print("Processing file: " + f.getName()+ "\n");
                String[] fileSplit = f.getName().split("_");
                towns.add(fileSplit[0]);

            }
        }

提前致謝

您正在檢查toString()而不是getName() - 也許目錄路徑包含下划線。

試試這個(注意簡化測試):

for(File f : files) {
    if (f.getName().matches(".*_.*\\.html")) {
        System.out.print("Processing file: " + f.getName()+ "\n");
        String[] fileSplit = f.getName().split("_");
        towns.add(fileSplit[0]);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM