如果一个文档中既有英文和符号,又有中文内容,可以调用RandomAccessFile中的seek();方法来逆置文档内容。
把握好文档中每个英文or符号占一个字节,中文会占两个字节的特点,利用它们在ASNI码中位置的不同来区分,具体实现如下:
RandomAccessFile rf=new RandomAccessFile(new File("D:/java2/ioText/text2.txt"),"r");
StringBuffer sb=new StringBuffer();
long lon= rf.length();
System.out.println(lon);
while (lon>0){
lon--;
rf.seek(lon);
byte a=rf.readByte();
if (a<=127 && a>=0){
sb.append((char) a);
}else {
lon--;
rf.seek(lon);
byte[] b=new byte[2];
rf.readFully(b);
System.out.println(new String(b,"gbk" ));
sb.append(new String(b,"gbk"));
}
}
System.out.println(sb);
也可以来用一个新的文档(若路径不存在则会新建)来接收新内容:
RandomAccessFile rf =
new RandomAccessFile(new File("D:/java2/ioText/text2.txt"),"r");
RandomAccessFile rfCp=
new RandomAccessFile(new File("D:/java2/ioText/rfCp.txt"),"rw");
long lon=rf.length();
while (lon>0){
lon--;
rf.seek(lon);
byte a=rf.readByte();
if (a<=127 && a>=0){
rfCp.write(a);
}else {
lon--;
rf.seek(lon);
byte[] b=new byte[2];
rf.readFully(b);
rfCp.write(b);
}
}
}