2014-09-25 74 views
3

目前我使用這樣的代碼我希望得到的子串

while (fileName.endsWith(".csv")) { 
     fileName = fileName.substring(0, fileName.lastIndexOf(FILE_SUFFIX_CSV)); 
     if (fileName.trim().isEmpty()) { 
      throw new IllegalArgumentException(); 
     } 
    } 

上面的代碼工作正常時,用戶指定小寫字母的擴展名(.CSV),但Windows接受擴展大小寫敏感的,所以他可以給像.CsV,.CSV等。我如何改變上面的代碼?

在此先感謝

+0

將文件名轉換爲小寫的花花公子 – 2014-09-25 05:54:54

+0

這已經在這裏得到了解答 - http://stackoverflow.com/questions/13620555/case-sensitive-file-extension-and-existence-checking – 2014-09-25 06:04:12

回答

11

爲什麼不把它變成小寫?

while (fileName.toLowerCase().endsWith(".csv")) { 
    fileName = fileName.substring(0, fileName.toLowerCase().lastIndexOf(FILE_SUFFIX_CSV)); 
    if (fileName.trim().isEmpty()) { 
     throw new IllegalArgumentException(); 
    } 
} 
+0

'filename.lastIndexOf(。 ..)'有同樣的問題。這也必須轉換爲小寫。除此之外:這就是答案! – Seelenvirtuose 2014-09-25 05:56:51

+0

@Seelenvirtuose這是答案,除非你需要在文件名中保存大小寫,這很可能。 – 2014-09-25 05:58:29

+0

@ThomasStets用'fileName.toLowerCase()。lastIndexOf(FILE_SUFFIX_CSV)'你不能改變變量。你只是在改變指數的計算。變量'fileName'仍被替換爲_original_字符串('fileName.substring(...)')的子字符串。 – Seelenvirtuose 2014-09-25 05:59:51

3

您可以將兩者都轉換爲大寫。

因此改變這一行

fileName = fileName.substring(0, fileName.lastIndexOf(FILE_SUFFIX_CSV)); 

fileName = fileName.toUpperCase().substring(0, fileName.lastIndexOf(FILE_SUFFIX_CSV.toUpperCase())); 
3

你可以試試這個方法

int lastIndexOfDot=fileName.lastIndexOf("\\."); 
String fileExtension=fileName.substring(lastIndexOfDot+1,fileName.length()); 
while(fileExtension.equalsIgnoreCase(".csv")){ 

} 

或者

while(fileName.toUpperCase().endsWith(".CSV"){} 
3

請轉換爲小寫,然後進行比較。

while (fileName.toLowerCase().endsWith(".csv")) { 
     fileName = fileName.toLowerCase().substring(0, fileName.toLowerCase().lastIndexOf(FILE_SUFFIX_CSV)); 
     if (fileName.toLowerCase().trim().isEmpty()) { 
      throw new IllegalArgumentException(); 
     } 
    } 
4

深夜正則表達式的解決方案:

Pattern pattern = Pattern.compile(".csv", Pattern.CASE_INSENSITIVE); 
Matcher matcher = pattern.matcher(fileName); 
while (matcher.find()) { 
    fileName = fileName.substring(0, matcher.start()); 
    if (fileName.trim().isEmpty()) { 
     throw new IllegalArgumentException(); 
    } 
} 

Matcher只會find()一次。然後它可以將其可用的start位置報告給substring原始文件名。