怎么用randomAccessFile进行文本文件的倒序输出:我的代码:
import java.io.*;
class resver {
public static void main(String args[]) { try { File f=new File("wo.txt");
RandomAccessFile a=new RandomAccessFile(f,"rw");
for(long i=f.length()-1;i>=0;i--)
{ a.seek(i*2);
System.out.println(""+a.readChar());
}
a.close();
} catch(IOException e) { System.out.print(e);}
}} 但存在异常,为什么
import java.io.*;
class resver {
public static void main(String args[]) { try { File f=new File("wo.txt");
RandomAccessFile a=new RandomAccessFile(f,"rw");
for(long i=f.length()-1;i>=0;i--)
{ a.seek(i*2);
System.out.println(""+a.readChar());
}
a.close();
} catch(IOException e) { System.out.print(e);}
}} 但存在异常,为什么
改成 a.seek(i);
你此时操作的是文件,是byte[]才对哦!
他才不管里面存的是啥呢!
class resver {
public static void main(String args[]) {
File f=new File("wo.txt"); try {
RandomAccessFile a=new RandomAccessFile(f,"rw");
for(long i=f.length()-1;i> =0;i--)
{ a.seek(i*2);
System.out.println(""+a.readChar());
}
a.close();
} catch(IOException e) { System.out.print(e);}
} }
这样试试~~~
import java.io.IOException;
import java.io.RandomAccessFile;public class Ceshi {
public static void main(String args[]) { try {
File f = new File("wo.txt");
RandomAccessFile a = new RandomAccessFile(f, "rw");
long i=0;
String ss=null;
char[] ch=null;
while(i<a.length()){
if(ss==null)
ss=a.readLine();
else
ss=ss.concat("\n"+a.readLine());
i=a.getFilePointer();
}
a.close();
ch=ss.toCharArray();
for(i=ch.length-1;i>=0;i--)
System.out.print(ch[(int)i]);
} catch (IOException e) {
e.printStackTrace();
}
}
}
然后你又 a.seek(i*2);
那这里指针不是跳了两倍总长了?