2013-09-01 12 views
21

内のテキストを書く私は、CSVファイルを読み込むコード内のテキストを編集し、.txtファイルに戻ってそれを記述しようとしています次のコード読むとANSI形式

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 

/** 
* 
* @author 
*/ 
import java.io.*; 


public class CSVConverter 
{ 
    private File csvFile; 
    private BufferedReader reader; 
    private StringBuffer strBuffer; 
    private BufferedWriter writer; 
    int startNumber = 0; 
    private String strString[]; 

    public CSVConverter(String location, int startNumber) 
    { 
     csvFile = new File(location); 
     strBuffer = new StringBuffer(""); 
     this.startNumber = startNumber; 


     //Read 
     try 
     { 
     reader = new BufferedReader(new FileReader(csvFile)); 
     String line = ""; 

     while((line=reader.readLine())!=null) 
     { 
      String[] array = line.split(","); 

      String inputQuery = "insertQuery["+startNumber+"] = \"insert into WordList_Table ('Engl','Port','EnglishH','PortugueseH','Numbe','NumberOf','NumberOfTime','NumberOfTimesPor')values('"+array[0]+"','"+array[2]+"','"+array[1]+"','"+array[3]+"',0,0,0,0)\""; 

      strBuffer.append(inputQuery+";"+"\r\n"); 
      startNumber++; 

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

     System.out.println(strBuffer.toString()); 

     //Write 
     try 
     { 
      File file = new File("C:/Users/list.txt"); 
      FileWriter filewrite = new FileWriter(file); 

      if(!file.exists()) 
      { 
       file.createNewFile(); 
      } 


      writer = new BufferedWriter(filewrite); 


      writer.write(strBuffer.toString()); 
      writer.flush(); 
      writer.close(); 

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

    } 

    public static void main(String[]args) 
    { 
     new CSVConverter("C:/Users/list.csv",90); 
    } 
} 

を見てください。私の問題はポルトガル語なので、ファイルはANSIの形式で読み書きする必要があります。現在、いくつかのポルトガル語が出力ファイルのシンボルに置き換えられています。

テキストデータをJavaでANSI形式のファイルに読み書きするにはどうすればよいですか?

+1

リスト farmacias = Files.readAllLines(Paths.get( "c:\\ tmp \\ Farmacias.txt")、Charset.forName( "Cp1252")); –

+0

私は同意しない> Windows用の適切なJavaエンコードANSIはCp1252ですANSIはマイクロソフトのトリックであり、設定できるエンコードの種類は異なります。 Windowsの設定に応じて、GBK、Shift_JISなどにすることもできます。 – TKJohn

答えて

41

特定のエンコードでテキストファイルを読むには、FileInputStreamInputStreamReaderを組み合わせて使用​​できます。 Windows ANSIの適切なJavaエンコーディングはCp1252です。

reader = new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), "Cp1252")); 

あなたはOutputStreamWriterと一緒FileOutputStreamを使用することができますコードする特定の文字を含むテキストファイルを書き込みます。

writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "Cp1252")); 

クラスInputStreamReaderOutputStreamWriter特定の文字エンコーディングでバイト指向のストリームとテキストの間の変換。

+1

なぜCp1252が一覧表示されないのですか(http://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html)? –

+3

おそらく、このリストは参考になります。http://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html – vanje

関連する問題