简单的实现:
先取得一个随机数,得到要取得的行号line,可参考:Math.random()方法
然后 读取第line行数据
BufferedReader in = new BufferedReader(new FileReader("filename"));
String str=null;
for(int i=0;(str = in.readLine()) != null&&i<=line;++i){; }
if(str!=null&&i==line){System.out.println("the text is:"+str);
}else{
System.out.println("no text that you want!");
}
in.close();
可能有更好的方法,仅供参考
先取得一个随机数,得到要取得的行号line,可参考:Math.random()方法
然后 读取第line行数据
BufferedReader in = new BufferedReader(new FileReader("filename"));
String str=null;
for(int i=0;(str = in.readLine()) != null&&i<=line;++i){; }
if(str!=null&&i==line){System.out.println("the text is:"+str);
}else{
System.out.println("no text that you want!");
}
in.close();
可能有更好的方法,仅供参考
解决方案 »
- 求助:如何读取一个文件夹里文件的文件名
- 为什么么不能清空content文本
- 请教if(conf ==true) {} 与if(true == conf){} 的区别和具体用法!
- Math.random与java.util.Random的区别
- 求一段代码
- 请问下用DELPHI和JAVA做一个C/S的小的管理信息系统谁更麻烦点,谢谢
- Servlet输出到excel文件乱码问题?
- 各位大侠,有谁知道用java怎么生成tif图?
- 如果TreeSet中存储的是整形的对象1,10,80,35,41,100......那么怎么指定它里面的元素按从小到大的顺序排列?排序后怎样将这个TreeSet中的元
- 再问java WEB图形 有关问题
- 菜鳥提問
- ★200分★ 求xml解析代码。从不提200分一下的问题。呵呵。
import java.io.RandomAccessFile代码sample:
rf = new RandomAccessFile("F:\\nepalon\\ rtest.dat", "r");
for(int i=0; i<10; i++){
System.out.println("Value " + i + ":" + rf.readDouble());
rf.seek(i);
rf.close();
}
import java.util.*;
public class TestFileDelete{
public static void main(String[] args){
System.out.println(getLine("aaa.txt",2));
}
public static String getLine(String fileName,int lineNumber){
File file=new File(fileName);
if(!file.exists() || file.isDirectory()){
return null;
}
String line=null;
LineNumberReader in=null;
try{
in=new LineNumberReader(new FileReader(file));
while(in.getLineNumber()+1!=lineNumber){
in.readLine();
}
line=in.readLine();
in.close();
in=null;
return line;
}
catch(IOException ioe){
if(in!=null){
try{
in.close();
}
catch(IOException ioee){
}
in=null;
}
System.out.println(ioe);
return line;
}
}
}
int s=r.nextInt(20)+1;//随机从第1-20行上取位置
rf = new RandomAccessFile("F:\\nepalon\\ rtest.dat", "r");
rf.seek(s);//移到随机的行数上
System.out.println("Value " + i + ":" + rf.readDouble());//读取
rf.close();