package filecollector;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.RandomAccessFile;
import java.util.Stack;
public class FileRead {
public static void main(String[] args) {
bufReader();
randomReader();
}
public static void bufReader(){
File file= new File("e:/test.txt");
Stack st = new Stack();
long currpos=0;
long startTime=System.currentTimeMillis();
try {
FileReader fileReader = new FileReader(file);
BufferedReader read = new BufferedReader(fileReader);
String line = null;
while ((line = read.readLine()) != null) {
if(line.startsWith("IE6")){
st.push(currpos);
}
currpos+=(line.length()+2);
}
if(st.size()>20000){
currpos=Long.valueOf(st.get(st.size()-20).toString());
}else{
currpos=0;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(currpos);
FileReader fileReader;
try {
fileReader = new FileReader(file);
BufferedReader read = new BufferedReader(fileReader);
read.skip(currpos);
System.out.println(read.readLine());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(System.currentTimeMillis()-startTime);
}
public static void randomReader(){
File file= new File("e:/test.txt");
long startTime=System.currentTimeMillis();
int count=0;
String line=null;
try {
RandomAccessFile randomReader = new RandomAccessFile(file, "r");
long filelen=randomReader.length()-1;
while(filelen>0&&count<20000){
randomReader.seek(filelen);
char c=(char)randomReader.read();
if(c =='\r'||c =='\n'){
line = randomReader.readLine();
if(line!=null&&line.startsWith("IE6")){
count++;
}
}
filelen--;
}
System.out.println(filelen);
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis()-startTime);
}
}
如果遇到随机读取文件,使用时最好先比较一下计算时间