关于编码的问题
该代码中,已经把“中”以gbk的方式进行存储,而后又以gbk编码的形式将其读取,为什么还会出现乱码?
该代码中,已经把“中”以gbk的方式进行存储,而后又以gbk编码的形式将其读取,为什么还会出现乱码?
2016-11-15
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
public class RafDome {
public static void main(String[] args) throws IOException {
File demo = new File("demo");
if(!demo.exists()){
demo.mkdir();
}
File file =new File(demo,"ra.dat");
if(!file.exists()){
file.createNewFile();
}
RandomAccessFile raf =new RandomAccessFile(file,"rw");
System.out.println(raf.getFilePointer());
String s="AB123456中国人民政府";
byte[] buf =s.getBytes("gbk");
System.out.println(buf.length);
raf.write(buf.length);
raf.write(buf);
raf.seek(0);
byte [] bu =new byte[(int)raf.read()];
raf.read(bu);
String str= new String(bu,"gbk");
System.out.println(str);
raf.close();
}
}
//这里我写了一个批量写入和读取
public class RandomAccessFileTest { public static void main(String[] args)throws IOException { File file1=new File("demo"); if(!file1.exists()) file1.mkdir(); File file2=new File(file1,"a.txt"); if(!file2.exists()) file2.createNewFile(); RandomAccessFile raf = new RandomAccessFile(file2, "rw"); //指针的位置 System.out.println(raf.getFilePointer()); raf.write('a');//只写一个字节 System.out.println(raf.getFilePointer()); raf.write('b'); System.out.println(raf.getFilePointer()); int i=0x7fffffff; raf.write(i>>>24);//写入后八位 System.out.println(raf.getFilePointer()); raf.write(i>>>16); System.out.println(raf.getFilePointer()); raf.write(i>>>8); System.out.println(raf.getFilePointer()); raf.write(i); System.out.println(raf.getFilePointer()); raf.writeInt(i); System.out.println(raf.getFilePointer()); String string="中"; byte[] byte1=string.getBytes("gbk"); raf.write(byte1);//汉字在gbk编码中占两个字节 System.out.println(raf.getFilePointer()); System.out.println("显示该文件的字节总长度:"+raf.length()); //进行读取操作,一次性将所有内容读取出来 raf.seek(0);//将指针的指向移动到开头 byte[] byte3=new byte[(int)raf.length()]; raf.read(byte3);//将文件的内容读到字节数组中 System.out.println(Arrays.toString(byte3)); String string3=new String(byte3,"gbk"); System.out.println(string3); } }
举报