37

请看下面的代码

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);
    }
}

我正在尝试读取 CSV 文件,编辑代码中的文本,然后将其写回.txt文件。ANSI我的问题是,我有葡萄牙语单词,所以文件应该使用格式读写。现在一些葡萄牙语单词在输出文件中被替换为符号。

如何在 Java 中以 ANSI 格式读取文本数据并将其写入文件?

4

1 回答 1

75

To read a text file with a specific encoding you can use a FileInputStream in conjunction with a InputStreamReader. The right Java encoding for Windows ANSI is Cp1252.

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

To write a text file with a specific character encoding you can use a FileOutputStream together with a OutputStreamWriter.

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

The classes InputStreamReader and OutputStreamWriter translate between byte oriented streams and text with a specific character encoding.

于 2013-09-01T14:31:22.850 回答