我想把一个文件尾部的空白字符删除,用RandomAccessFile实现,但实现不了.
不知道是readChar()用的不对还是seek()用的不对,希望高手指导:
下面是我的程序import java.io.*;
public class TestAccessFile{
    public static void main (String[] args) {
       try{
       RandomAccessFile raf=new RandomAccessFile("test.txt","rw");
       long pos=raf.length()-2;   
       raf.seek(pos);                //定位到pos
       char ch=raf.readChar();        //读取一个字符
       while(Character.isWhitespace(ch)) {     //是不是空白字符
       pos--;                            
       raf.seek(pos);         
       ch=raf.readChar();
       }
       System.out.println(raf.getFilePointer()+" "+pos);
       raf.setLength(raf.getFilePointer());              //文件长度改为当前文件指针的值(对应文件开始的偏移量)
       raf.close();
       }catch(Exception e){
       e.printStackTrace();
       }
    }
}

解决方案 »

  1.   

    import java.io.*;
    public class haogasg{
        public static void main (String[] args) {
           try{
               RandomAccessFile raf=new RandomAccessFile("test.txt","rw");
                  long pos=raf.length()-3;   
                  raf.seek(pos);                //定位到pos
                  int ch=raf.read();        //读取一个字符
                  while(Character.isWhitespace(ch)) {     //是不是空白字符
                      pos = pos-1;                            
                      raf.seek(pos);         
                      ch=raf.read();
                  }
                  
                System.out.println(raf.getFilePointer()+" "+pos);
                  raf.seek(pos);
                  raf.setLength(pos+1);              //文件长度改为当前文件指针的值(对应文件开始的偏移量)
                  raf.close();
              }catch(Exception e){
                  e.printStackTrace();
              }
        }
    }楼主,我帮你改好了
      

  2.   

    有句话写错了
    第六行:long pos=raf.length()-1;
      

  3.   

    我觉得还是读到 字符串中,然后用 trim,
      

  4.   

    1楼,我运行了,-1,-3都不行。3楼,你的办法是可以的。那样要把文件全部的内容一行行的读,全读到一个CharSequence中,效率不太高。所以我想用RandomAccessFile或者FileChannel来实现。这样只处理最后的那些空白字符就可以了。
      

  5.   


    FileChannel 也可以转成文本吧.....