我有一個字符串,它可以改變:獲取特定字符串中的字符
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
嘗試:'String filePath3 = filePath.replace(filePath2,「」);' - 所以得到原始文件(完整路徑)。 – 2014-12-05 19:39:12
String filePath3 = filePath.substring(0,filePath.lastIndexOf(「/」)+ 1); – aadi53 2014-12-05 19:44:02