2014-12-05 6 views
0

문자열의 특정 문자를 받기다를 수 있습니다 내가 문자열을

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

나는이 방법을 시도를하지만 실패 (충돌) :

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, "");'- 원본 (전체 경로)을 얻으려면 - 파일. –

+0

방법 문자열 filePath3 filePath.substring = (0, filePath.lastIndexOf ("/") + 1); – aadi53

답변

3

Java의 File 클래스는 어떻습니까?

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

왜 for 루프가 있습니까?

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

File 클래스를 사용할 수 있습니다. 이 \/을 변경할 수 있지만,이 파일에 관련된 다른 API에 인수로이 결과를 사용하려는 경우이 변경에 문제가 안된다는

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 

참고.

관련 문제