简体   繁体   中英

CSV displaying japanese hankaku(half-width) instead of zenkaku(full-width) in java

I am generating csv file using Java Bufferedwriter. I am trying to append zenkaku(full-width) number to csv file, but it is displaying hankaku instead of zenkaku. Can you suggest me to how to do this? Below is my sample code.

public class GenerateCSVProg {

private static StringBuffer sb = null;
private static BufferedWriter bw = null;
private static GenerateCSVProg writer = null;

public GenerateCSVProg(String fileName) throws Exception{
    init(fileName);
}

private void init(String fileName) throws Exception{

    try { 
    bw= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName)));

    } catch (FileNotFoundException e) {
        throw e;
    }
}

/**
 * @param args
 */
public static void main(String[] args) {
    generateCsvFile("c:\\work\\test.csv"); 
}

private static void generateCsvFile(String fileName){
    try{
        writer = new GenerateCSVProg(fileName);
        System.out.println("Entered in generateCsvFile method");

            writer.append("DisplayName");
            writer.append(",");
            writer.append("Age");
            writer.append("\n");

            writer.append("MKYONG");
            writer.append(",");
            writer.append("26");
            writer.append("\n");

            writer.append("SIVA");
            writer.append(",");
            writer.append("29"); // zenkaku
            writer.append("\n");
            System.out.println("Entered in generateCsvFile method: " + writer);

            //generate whatever data you want
            bw.write(sb.toString());
            System.out.println("Code break");
            if(writer!=null){
                writer.close();
            }
    }catch (Exception e) {
        System.out.println("Exception occurred");
    }
    finally {

    }   
}

public void append(String out){
    if (sb == null){
        sb = new StringBuffer();    
    }
    sb.append(out);
    System.out.println("SB: " + sb);
}

public static void close() throws Exception{    
    if (bw != null){
        bw.close();
    }
}

}

Output:

DisplayName Age
MKYONG      26
SIVA        29 // Here it is displaying hankaku

Please help me on this..

It works fine for me. Your system may not be outputting to UTF-8 as a default. You should always specify when you are using OutputStreamWriter. Change it to look like this:

bw= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM