我想把一个文件尾部的空白字符删除,用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();
}
}
}
不知道是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();
}
}
}
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();
}
}
}楼主,我帮你改好了
第六行:long pos=raf.length()-1;
FileChannel 也可以转成文本吧.....