用RandomAccessFile处理中文的时候,总是在读到最后的时候出现EOFException,或者出现乱码,请各位帮我看看,多谢下面是源码:
输入是cutoff.txt,内容是"你们可好"
希望运行后cutoff.txt的内容是"可好可好"import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;public class CutOff {
private static String sourceFile = "cutoff.txt";
public static void main(String[] args){
try {
RandomAccessFile accessor = new RandomAccessFile(sourceFile,"rw");
long length = accessor.length()/2;
long readIndex = length;
long writeIndex = 0;
byte b;
char c;
for(;writeIndex<length;){
accessor.seek(readIndex);
b = accessor.readByte();
if(b<0){
c = accessor.readChar();
accessor.seek(writeIndex);
accessor.writeChar(c);
readIndex = readIndex + 2;
writeIndex = writeIndex + 2;
}else{
accessor.seek(writeIndex);
accessor.writeByte(b);
readIndex++;
writeIndex++;
}
}
accessor.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex){
ex.printStackTrace();
}
}
}
输入是cutoff.txt,内容是"你们可好"
希望运行后cutoff.txt的内容是"可好可好"import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;public class CutOff {
private static String sourceFile = "cutoff.txt";
public static void main(String[] args){
try {
RandomAccessFile accessor = new RandomAccessFile(sourceFile,"rw");
long length = accessor.length()/2;
long readIndex = length;
long writeIndex = 0;
byte b;
char c;
for(;writeIndex<length;){
accessor.seek(readIndex);
b = accessor.readByte();
if(b<0){
c = accessor.readChar();
accessor.seek(writeIndex);
accessor.writeChar(c);
readIndex = readIndex + 2;
writeIndex = writeIndex + 2;
}else{
accessor.seek(writeIndex);
accessor.writeByte(b);
readIndex++;
writeIndex++;
}
}
accessor.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex){
ex.printStackTrace();
}
}
}
{
accessor.seek(readIndex);
c = accessor.readChar();
accessor.seek(writeIndex);
accessor.writeChar(c);
readIndex = readIndex + 2;
writeIndex = writeIndex + 2;
}
判断小于零说明是中文字符
然后应该读取一个字符
但是此时的readIndex已经加了1
要重新定位到原读取位置