最近在学习文件的随机读访问 就做了下面的代码来试验RandomAccessFile类的功能,只试验了一下读写!希望能给大家一些帮助,我还在继续学习中 最近还会发些关于IO的帖子,希望大家支持
以下是代码:
package ClassFile;
import java.io.RandomAccessFile;
import java.io.File;
import java.io.IOException;
import java.io.FileOutputStream;
public class TryRandomAccessFile {
private File file;
public TryRandomAccessFile() {
setPath("../文件实例/ClassFile");//设置文件路径所有的目录都要存在
}
public TryRandomAccessFile(String file){
setPath(file);
}
public void setPath(String file){
this.file=new File(file);
}
public void outToFile(){
outToFile("It's good boy\r\n");
}
public void outToFile(String news){
outToFile("temp.txt",news);
}
public void outToFile(String fileName,String news){
File f=new File(this.file.getPath()+"\\"+fileName);
try{
FileOutputStream out=new FileOutputStream(f);
out.write(news.getBytes());
news="num:3";
out.write(news.getBytes());
}catch(IOException io){
System.out.println(io.toString());
}
}
public void edit(String fileName){//试验读写文件后,指针停留的位置
try{
RandomAccessFile raf=new RandomAccessFile(new File(this.file.getPath()+"\\"+fileName),"rw");
String s=raf.readLine();
System.out.println(s+"\r\n"+raf.readLine()+"\r\n"+raf.getFilePointer());
raf.seek(measure(s,raf));
raf.write("115".getBytes());
raf.seek(0);
s=raf.readLine();
System.out.println(s+"\r\n"+raf.readLine());
//System.out.println(raf.readLine());
//System.out.println(raf.readLine());
//System.out.println(raf.readLine()); //得到null值 但不引起异常
raf.close();
}catch(IOException io){
System.out.println(io.toString());
}
}
public long measure(String find,RandomAccessFile raf){
String s;
long flag=0;
try{
raf.seek(0);
s=raf.readLine();
if(find!=""){
while(!(s.contains(find))){
flag=flag+s.length();
flag+=2;
s=raf.readLine();
}
}
}catch(IOException io){
System.out.println(io.toString());
}
flag=find.indexOf(':')+1;
return flag;
}
public static void main(String args[]){
TryRandomAccessFile traf=new TryRandomAccessFile();
traf.outToFile("default:0 \r\n");
traf.edit("temp.txt");
}
}
没有评论:
发表评论