【问题标题】:Read and Write Text in ANSI format以 ANSI 格式读取和写入文本
【发布时间】:2013-09-04 13:15:38
【问题描述】:

请看下面的代码

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 格式的文件中?

【问题讨论】:

  • List farmacias = Files.readAllLines(Paths.get("c:\\tmp\\Farmacias.txt"), Charset.forName("Cp1252"));
  • 我不同意> Windows ANSI 正确的Java 编码是Cp1252 ANSI 是微软的诡计,可以设置成不同的编码。也可以是GBK、Shift_JIS等,视Windows的设置而定。

标签: java io bufferedreader ansi bufferedwriter


【解决方案1】:

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

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

要编写具有特定字符编码的文本文件,您可以使用FileOutputStreamOutputStreamWriter

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
  • 2016-10-06
  • 2012-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多