2014-12-05 58 views
0

我有一個字符串,它可以改變:獲取特定字符串中的字符

String filePath = "/this/is/my/file.txt"; 

我需要得到這個字符串信息等字符串:

"/this/is/my" and "file.txt" 

這個方法我試過,但它失敗(crash):

int counter = 0; 
    filePath = "/this/is/my/file.txt"; 
    String filePath2 = filePath.substring(filePath.lastIndexOf("/") + 1); // return "file.txt" 
    for (int i = 0; i < filePath2.length(); i++) { 
     counter++; // count number of char on filePath2 
    } 
    String filePath3 = filePath3.substring(filePath.lastIndexOf("") + counter); // Remove "file.txt" from filePath2 depending of character numbers on filePath2 backwards 

有人知道更好的方法嗎?謝謝!

12-05 15:53:00.940 11102-11102/br.fwax.paulo.flasher E/AndroidRuntime﹕ FATAL EXCEPTION: main 
    Process: br.fwax.paulo.flasher, PID: 11102 
    java.lang.RuntimeException: Unable to start activity ComponentInfo{br.fwax.paulo.flasher/br.fwax.paulo.flasher.MFlasher}: java.lang.StringIndexOutOfBoundsException: length=21; index=29 
+0

嘗試:'String filePath3 = filePath.replace(filePath2,「」);' - 所以得到原始文件(完整路徑)。 – 2014-12-05 19:39:12

+0

String filePath3 = filePath.substring(0,filePath.lastIndexOf(「/」)+ 1); – aadi53 2014-12-05 19:44:02

回答

3

Java的File類怎麼樣?

File f = new File(filePath); 
String directory = f.getParent(); 
String fileName = f.getName(); 
3

爲什麼你甚至有你的循環?

int index = filePath.lastIndexOf("/"); 
String firstString = filePath.substring(0, index); 
String secondString = filePath.substring(index+1, filePath.length()); 
1

您可以使用File類。

String filePath = "/this/is/my/file.txt"; 

File f = new File(filePath); 

System.out.println(f.getParent());// \this\is\my 
System.out.println(f.getName());// file.txt 

注意,這可以改變/\,但如果你要在相關文件中其他的API來使用此結果作爲參數,不應該有這種變化的任何問題。

相關問題