2016-12-28 9 views
1

루프 중에 내 목록에 CSV 파일이 들어 있는데 출력 결과를 저장하는 파일 이름을 얻고 싶습니다.목록에서 파일 이름을 추출하십시오.

:

파일 목록 : t1.csv, t2.csv, t3.csv

출력 목록이 표시되어야합니다 t1.xml, t2.xml, t3.xml

sample.java

List<String> csvFiles = new ArrayList<String>();        
try { 
    File[] files = new File(textCSV.getText()).listFiles(); 
    for (File file : files) { 
     if (file.isFile()) { 
      csvFiles.add(file.getName()); 
     } 
    } 
    for(int i=0;i<csvFiles.size();i++) { 
     System.out.println(csvFiles.get(i));       
     String Output = ".xml" //how to put here csv name 
    } 
} 
+1

'System.out.println (csvFiles.get (i) .replace (".csv", ".xml")); ' – shmosel

+0

thx, 잘 작동합니다! – 4est

답변

1

이렇게하면 다시 쓸 수 있습니다.

List<String> csvFiles = new ArrayList<String>();        
    try { 
     File[] files = new File(textCSV.getText()).listFiles(); 
     for (File file : files) { 
      if (file.isFile()) { 
       csvFiles.add(file.getName()); 
      } 
     } 
     for(int i=0;i<csvFiles.size();i++) 
     { 
      System.out.println(csvFiles.get(i));    

      String Output = csvFiles.get(i).substring(0, csvFiles.get(i).indexOf(".")) + ".xml" //how to put here csv name 
     } 
    } 
+0

감사합니다. 작동 중입니다. – 4est

+2

파일에 둘 이상의 "."가 포함되어있을 경우'indexOf'를'lastIndexOf'로 대체해야합니다. (점) 파일 이름에 :) –

1

파일 이름 만 추출 할 수있는 방법에는 3 가지가 있습니다. 아파치 코 몬즈 도서관 경우

FilenameUtils.removeExtension(file.getName()); 
  • 를 사용

    1. 파일는 항상 포함하는 적어도 하나의 확장 (적어도 하나 "."에있는 파일 이름)

      file.getName().substring(0, file.getName().lastIndexOf(".")); 
      
    2. 확장자가없는 파일이있는 경우

      int index = file.getName().lastIndexOf("."); 
      if (index == -1) { 
          file.getName(); 
      } else { 
          file.getName().substring(0, index); 
      } 
      

    당신은 위의 라인의로 csvFiles.add(file.getName());csvFiles.add();에 인수를 대체 할 수 있습니다.