Java中RadomAccessFile读写操作参见我写的示例: 第一部分,创建或添加文本到指定文件的未尾(如文件不存在则创建,如存在是追加,其中文件指针的定位用 .length()得到文件总长,.seek()来定位. import java.io.*;public class TestWrite{
public static void main(String[] args){
//先创打开一个文件,如不存在,则创建一个
try{
String str;
byte[] s;
RandomAccessFile rf=new RandomAccessFile("temp.txt","rw");
long count=rf.length();
rf.seek(count);
//如要换行,用 \r\n 次序不要乱
for(int i=0;i<4;i++){
str="这是第 "+i+"行文本示例\r\n";
s=str.getBytes();
rf.write(s);
}
rf.close();
}catch(Exception e){
System.err.println("读写出错");
}
}
} 第二部分,读出并显示:
import java.io.*;public class TestRead{
public static void main(String[] args){
try{
RandomAccessFile rf=new RandomAccessFile("temp.txt","rw");
String str="";
int count=(int)rf.length();
//注意,此处我把long转换为int,实际操作中文件较大时,你还用long
//但分成若干次读入,一次读一部分。
byte[] s=new byte[count];
rf.read(s);
str=new String(s);
System.out.println(str);
rf.close();
}catch(Exception e){
}
}}
public static void main(String[] args){
//先创打开一个文件,如不存在,则创建一个
try{
String str;
byte[] s;
RandomAccessFile rf=new RandomAccessFile("temp.txt","rw");
long count=rf.length();
rf.seek(count);
//如要换行,用 \r\n 次序不要乱
for(int i=0;i<4;i++){
str="这是第 "+i+"行文本示例\r\n";
s=str.getBytes();
rf.write(s);
}
rf.close();
}catch(Exception e){
System.err.println("读写出错");
}
}
} 第二部分,读出并显示:
import java.io.*;public class TestRead{
public static void main(String[] args){
try{
RandomAccessFile rf=new RandomAccessFile("temp.txt","rw");
String str="";
int count=(int)rf.length();
//注意,此处我把long转换为int,实际操作中文件较大时,你还用long
//但分成若干次读入,一次读一部分。
byte[] s=new byte[count];
rf.read(s);
str=new String(s);
System.out.println(str);
rf.close();
}catch(Exception e){
}
}}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货