当前页面: 开发资料首页 → J2SE 专题 → 用RandomAccessFile处理中文的问题 
用RandomAccessFile处理中文的问题 
摘要: 用RandomAccessFile处理中文的问题  
用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
                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();
        }
    }
}
if(b < 0)
{
accessor.seek(readIndex);
c = accessor.readChar();
accessor.seek(writeIndex);
accessor.writeChar(c);
readIndex = readIndex + 2;
writeIndex = writeIndex + 2;
}
以为你先读了一个字节b了
判断小于零说明是中文字符
然后应该读取一个字符
但是此时的readIndex已经加了1
要重新定位到原读取位置
哈哈,这么快就发现了,我想了足足大半天
高手,多谢
结帖