2015-01-13 2 views
0

CSV 파일에있는 요소를 arraylist에 할당해야합니다. CSV 파일에는 확장명이 .tar 인 파일 이름이 들어 있습니다. 배열 목록을 읽거나 전체 arraylist를 다듬기 전에 해당 요소를 다듬어야합니다. 당신이 당신의 토큰에서 ".tar가"문자열을 제거 할 경우 사용할 수 있습니다, 그것은배열 목록에 요소를 지정하기 전에 요소를 트리밍하는 방법은 무엇입니까?

try 
    { 
    String strFile1 = "D:\\Ramakanth\\PT2573\\target.csv"; //csv file containing data 
    BufferedReader br1 = new BufferedReader(new FileReader(strFile1)); //create BufferedReader 
    String strLine1 = ""; 
    StringTokenizer st1 = null; 

    while((strLine1 = br1.readLine()) != null) //read comma separated file line by line 
    { 
    st1 = new StringTokenizer(strLine1, ","); //break comma separated line using "," 

    while(st1.hasMoreTokens()) 
    { 
     array1.add(st1.nextToken()); //store csv values in array 
    } 
    } 
    } 
    catch(Exception e) 
    { 
    System.out.println("Exception while reading csv file: " + e);     
    } 
+0

해당 요소를 건너 뛰어도 되겠습니까 (목록에 추가하지 마십시오)? 그러면 간단한 'if'문이 도움이됩니다. – Thilo

답변

0

좀 도와주십시오

당신의 JavaDoc을 말한다 StringTokenizer를 (사용하지 않아야
String nextToken = st1.nextToken(); 
if (nextToken.endsWith(".tar")) { 
    nextToken = nextToken.replace(".tar", ""); 
} 
array1.add(nextToken); 
+0

'endsWith (".tar")' –

+0

뒤에 닫는 괄호가 누락 된 것 같습니다. –

0

부분) StringTokenizer은 새로운 코드에서 사용을 권장하지 않지만 호환성 이유로 보존되는 레거시 클래스입니다. 이 기능을 원하는 사람은 split 메서드를 String 또는 java.util.regex 패키지로 대신 사용하는 것이 좋습니다.BufferedReader을 닫아야합니다. 그러려면 try-with-resources statement을 사용할 수 있습니다. 그리고, 당신은 String.split(String) 아래 정규 표현식이 선택적으로 전이나 , 후 공백과 일치하고 루프를 continue 수에 의해 생성 된 배열을 반복하는 for-each loop를 사용할 수있는 경우

String strFile1 = "D:\\Ramakanth\\PT2573\\target.csv"; 
try (BufferedReader br1 = new BufferedReader(new FileReader(strFile1))) 
{ 
    String strLine1 = ""; 
    while((strLine1 = br1.readLine()) != null) { 
    String[] parts = strLine1.split("\\s*,\\s*"); 
    for (String token : parts) { 
     if (token.endsWith(".tar")) continue; // <-- don't add "tar" files. 
     array1.add(token); 
    } 
    } 
} 
catch(Exception e) 
{ 
    System.out.println("Exception while reading csv file: " + e);     
} 
+0

좋은 조언이 있지만, tar 파일을 자르는 것에 대한 질문에는 답변하지 않습니다. . – Thilo

+0

("파일 이름 주위에 공백 자르기"를 의미하지 않는 한 ...) – Thilo

+0

@Thilo tar 파일을 건너 뛰도록 편집되었습니다. –

0
while(st1.hasMoreTokens()) 
{ 
    String input = st1.nextToken(); 
    int index = input.indexOf("."); // Get the position of '.' 

    if(index >= 0){  // To avoid StringIndexOutOfBoundsException, when there is no match with '.' then the index position set to -1. 
     array1.add(input.substring(0, index)); // Get the String before '.' position. 
    } 
} 
0
같은 token endsWith "를 .tar"
if(str.indexOf(".tar") >0) 
str = str.subString(0, str.indexOf(".tar")-1); 
관련 문제