尽管以前的规范,PrintWriter println()不会打印出UTF-8编码

时间:2014-02-23 14:58:07

标签: java utf-8

我遇到printWriter写入已经创建的.txt文件的问题。虽然在创建PrintWriter对象时,我指定我想使用UTF-8格式,但在尝试打开输出文件时(使用gedit-sudo gedit-nano)我看到的都是不可读的和一些中文字符(我假设它们是中文) 。更令人费解的是,当打印出我要插入文件到标准输出(system.out.println)的数据时,数据打印正常!此外,在通过终端将输出文件填充到文件名后执行file命令,所有命令返回的是" file-name.txt:data",而不是我希望看到的UTF-8 !我包括相关的代码,提前感谢任何建议。

我用来汇总我想要打印的数据的功能:

public String DumpData(){
    String dump = "\0";
    dump = dump.concat(Long.toString(MessageID)).concat(",").concat(Long.toString(userID)).concat(",").concat(UserScreenName).concat(",").concat(Float.toString(Latitude)).concat(",").concat(Float.toString(Longitude)).concat(",").concat(Location).concat(",").concat(MessageDate).concat(",").concat(Integer.toString(IsFavourite)).concat(",").concat(Integer.toString(FollowersCount)).concat(",").concat(Integer.toString(FollowingsCount)).concat(",").concat(Integer.toString(Mentions)).concat(",").concat(Integer.toString(URLCount)).concat(",").concat(Integer.toString(Anger_CNT)).concat(",").concat(Integer.toString(Disgust_CNT)).concat(",").concat(Integer.toString(Fear_CNT)).concat(",").concat(Integer.toString(Sadness_CNT)).concat(",").concat(Integer.toString(Surprise_CNT)).concat(",").concat(Integer.toString(Joy_CNT)).concat(",").concat(Integer.toString(Exclam)).concat(",").concat(Integer.toString(Questions)).concat(",").concat(Integer.toString(Quotations)).concat(",").concat(Integer.toString(IS_RT)).concat(",").concat(Integer.toString(Caps)).concat(",").concat(Integer.toString(Smalls)).concat(",").concat(Integer.toString(Emotion));
    return dump;
}

我创建PrintWriter对象并尝试打印到文件并打印到标准输出的段:

try {
        PrintWriter out = null;
        try {
            //out = new PrintWriter("/home/mark/Desktop/datamining/tweetfiles/annotatedTweets.csv", "UTF-8");
            out = new PrintWriter("/home/mark/Desktop/datamining/tweetfiles/tweetsafterannotation.txt","UTF-8");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Testingtwitter.class.getName()).log(Level.SEVERE, null, ex);
        }
        for(int i=0; i<mydata.size(); i++){
            System.out.println(mydata.get(i).DumpData());
            out.println(mydata.get(i).DumpData());
        }
        out.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Testingtwitter.class.getName()).log(Level.SEVERE, null, ex);
    }

0 个答案:

没有答案