2017-02-09 2 views
1

저는 초보자이며 apache.poi 라이브러리를 사용하여 CSV 파일에 데이터를 쓰려고합니다. csvPrinter은 csv 파일에 데이터를 쓸 수 없습니다.은 CSV 파일에 데이터를 쓸 수 없습니다.

URL dir = getClass().getClassLoader().getResource("csv/input.csv"); 
File file = new File(dir.getFile()); 
FileWriter fileWriter = new FileWriter(file); 
CSVPrinter csvPrinter = new CSVPrinter(fileWriter, csvFileFormat); 
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(","); 
csvPrinter.print(data); 

편집

이 코드입니다.

FileWriter fileWriter = null; 
    CSVPrinter csvPrinter = null; 
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(","); 
    Logger logger = LoggerFactory.getLogger(this.getClass()); 

    { 
     try{ 
      URL dir = getClass().getClassLoader().getResource("csv/input.csv"); 
      File file = new File(dir.getFile()); 
      fileWriter = new FileWriter(file); 
      csvPrinter = new CSVPrinter(fileWriter, csvFileFormat); 
     }catch(Exception e){ 
      System.out.println(e.getMessage()); 
     } 
    } 

    @Override 
    public void write(List<? extends String[]> messages) throws Exception { 

     String[] data = messages.iterator().next(); 
     csvPrinter.print(data); 
     for (String singleData : data) { 
      System.out.println(singleData); 
     } 
//  csvwriter.close(); 
    } 
+0

데이터 변수에는 무엇이 있습니까? – Tschallacka

+0

구체적으로 작성하십시오. 오류가 있습니까? 런타임 또는 컴파일 오류? 전체 오류 메시지를 표시하십시오. 런타임 오류의 경우 전체 스택 추적도 표시하십시오. – vanje

+0

선언되기 전에'csvFileFormat'을 사용했습니다. 왜? –

답변

0

poi에 바인딩되어 있습니까? 이것을 시도하지 않으면.

public static void main(String[] args) { 
     // TODO code application logic here\\ 

     Random random = new Random(); 
     StringBuilder stringbuilder = new StringBuilder(); 

     //make random data file 
     for(int i = 1; i <= 100; i++) 
     { 
      stringbuilder.append(random.nextInt(10000) + 1).append(",");//append data and comma 
      if(i % 10 == 0) 
      { 
       stringbuilder.append("\r\n");//add new line at end of one line of data 
      } 
     } 

     //creat the file that the data will be written to 
     File file = new File("results.csv"); 

     //write the string data to file 
     try(FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw)) 
     {   
      bw.write(stringbuilder.toString()); 
     } 
     catch (IOException ex) 
     { 
      System.out.println("Something went wrong!"); 
     } 


     //open the file with your default program 
     try 
     { 
      Desktop.getDesktop().open(file); 
     } 
     catch (IOException ex) { 
      Logger.getLogger(Writecvsfile.class.getName()).log(Level.SEVERE, null, ex); 
      System.out.println("Can't open file!"); 
     } 
    } 
관련 문제