ubuntu 下java写txt文件,编码问题

ubuntu下用java直接用FileWriter写入到一个txt文件中之后,由于默认编码的缘故,不能使用gedit打开该txt。

在将String写入到txt之前,先转换一下编码,就可以解决问题。

实例代码如下:

import java.io.FileWriter; import java.io.IOException; public class testcode { public static void main(String[] args){ try { String s = "naughty 是一个中国人"; FileWriter fw = new FileWriter("a.txt"); // String(byte[] bytes, String charsetName) // 构造一个新的 String,方法是使用指定的字符集解码指定的字节数组。 s = new String(s.getBytes("GB18030"),"GB18030"); // byte[] getBytes(String charsetName) // 使用指定的字符集将此 String 解码为字节序列,并将结果存储到一个新的字节数组中。 fw.write(s); fw.flush(); } catch (IOException ex) { ex.printStackTrace(); } System.out.print("naufasdf"); } }


对于读取文件的时候,由于不知道已经存在的txt文件的编码格式,可以用挨个尝试的方法来确定txt的编码格式

测试代码如下:

    BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream("a.txt"),"GBk")); String line = null; line = bf.readLine(); while (line != null) { System.out.println(line); line = bf.readLine(); }  

其中,GBK可以换成GB2312,UNICODE,UTF-8等编码格式来测试原来的txt的编码方式。





你可能感兴趣的:(java,String,ubuntu,测试,null,byte)