以 ANSI 格式读取和写入文本

2022-09-01 05:02:33

请看下面的代码

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 文件,编辑代码中的文本,然后将其写回文件。我的问题是,我有葡萄牙语单词,所以文件应该使用格式读取和写入。现在,一些葡萄牙语单词被替换为输出文件中的符号。.txtANSI

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


答案 1

要读取具有特定编码的文本文件,可以将 与 结合使用。Windows ANSI 的正确 Java 编码是 。FileInputStreamInputStreamReaderCp1252

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

要编写具有特定字符编码的文本文件,可以将 与 一起使用。FileOutputStreamOutputStreamWriter

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

在面向字节的流和具有特定字符编码的文本之间进行类和转换。InputStreamReaderOutputStreamWriter


答案 2

推荐