2016-12-22 16 views
0

データをCSVファイルに保存します。私はスキャナーを使用してCSVWriterを読み込んで保存しています。CSVWriterはファイルに書き込むことを許可していません

エラーが発生しました:互換性のない型:List [String]をString []に変換できません。

方法:

private static void insertToFile(String source, String target) 
{ 
    List<String> data = new ArrayList<String>(); 
    try{ 
    Scanner sc = new Scanner(new File(source)); 

    while (sc.hasNextLine()) { 
     data.add(sc.nextLine()); 
    } 
    sc.close(); 
    } 
    catch(Exception e){ 
    e.printStackTrace(); 
    } 

     File resfile = new File(target);  

     try{ 
      CSVWriter writer = new CSVWriter(new FileWriter(resfile, true)); 

      //BufferedWriter bufferedWriter = new BufferedWriter(writer); 

      for (String j : data) { 
       //writer.writeAll(data);//error here 
      } 

       writer.close(); 
      } 
     catch(Exception e){ 
       e.printStackTrace(); 
     } 
    } 
+0

'writeAll()'に配列を渡す必要がある場合は、直接リストを渡すことはできません。まずそれを変換してみてください。 'writer.writeAll(data.toArray(new String [])'。 – Thomas

+0

あなたは 'for writer.writeAll(data.toArray(new String []))'を書く必要はありません ' – Babel

答えて

1

問題が

writer.writeAllを入力としてString[]を受け入れることで、あなたがから

for (String j : data) { 
    //writer.writeAll(data);//error here 
} 

を変更List<String>

を渡しています

writer.writeAll(data.toArray(new String[data.size()]));が問題を解決します。

+0

ありがとうございました@Jobin! – 4est

0

代わりにこれを試してみてください:

private static void insertToFile(String source, String target) 
{ 
    List<String> data = new ArrayList<>(); 

    // utilize Scanner implementing AutoCloseable and try-with-resource construct 
    // see https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) 
    try (Scanner sc = new Scanner(new File(source))) { 
     while (sc.hasNextLine()) { 
      data.add(sc.nextLine()); 
     } 
    } 
    catch (Exception e){ 
     e.printStackTrace(); 
    } 

    File resfile = new File(target); 

    try { 
     // depending on the CSVWriter implementation consider using try-with-resource as above 
     CSVWriter writer = new CSVWriter(new FileWriter(resfile, true)); 

     writer.writeAll(data.toArray(new String[data.size()])); 

     writer.close(); 
    } 
    catch (Exception e){ 
     e.printStackTrace(); 
    } 
} 

は、それはあなたのリストの長さに初期化配列にリストを変換します。また、リスト内の各要素についてリスト全体にwriteAllを呼びたくない場合は、リストをファイルに複数回印刷します。

0

これを行う簡単な方法があります。下記のコードを使用することができます。 これらの依存関係をコード内にインポートします(java.io.Fileのインポート、java.io.FileWriterのインポート)。

FileWriter writer = new FileWriter(new File(File_path)); 
writer.write(data); 
writer.close(); 
+0

あなたが受け取ったエラー – 4est

+0

がありますか? –

+0

ファイルresfile = new File(target).....からすべてを削除してコードを入れました。 write(List [String]) – 4est

関連する問題