<pre name="code" class="java"> public class BufferreadDemo {
static long n;//定义静态变量n为了记录每次读取的文件指针
//本文以从文件中读取字符串并转化为整形为例说明
public int[] transform(int size) {
String s =null;
//将文件读取操作全部放到try catch中以防止每次调用都要抛出异常
try {
//实现文件的随机读取
RandomAccessFile in = new RandomAccessFile("./data/realdata.txt","r");
//从第n个位置开始读取文件(n是上次读取后文件指针的位置)
in.seek(n);
//从文件中读出字符串
s = in.readLine();
//将此次读取后文件的指针位置赋给n为了便于下次从此处开始读取
n=in.getFilePointer();
} catch(IOException e){
e.printStackTrace();
}
//System.out.println(n);
if(s!=null){
System.out.println("读出的字符串是:"+s);
//每行字符串的长度
int le=s.length();
//System.out.println("读出的字符串长度是:"+le);
byte[] byteBuffer = new byte[le];
int[] a = new int[size];
int count = 0;
//将String转换为byte数组
byteBuffer = s.getBytes();
for(int i=0;i<le;i++){
int x = byteBuffer[i];
}
System.out.println();
for(int i=0;i<le;i++){
if (byteBuffer[i]>0&&byteBuffer[i]<256){
a[count] = byteBuffer[i];
count++;
}
else{
System.out.println("數據異常!");
}
}
return a;
}
else{
System.out.println("已經到文件末尾");
n=0;
return null;
}
}
}
//定义测试主函数
public class TestDemo {
public static void main(String[] args) throws IOException {
int [] a = new int[20];
//实现两次读取看是否是从本次读取后的位置开始读取
a= new BufferreadDemo().transform();
for(int n:a){
System.out.print(n+" ");
}
a= new BufferreadDemo().transform();
for(int n:a){
System.out.print(n+" ");
}
System.out.println();
String s = new BufferreadDemo().transString(a);
System.out.println(s);
}
}
JAVA IO流RandomAccessFile随机读取
最新推荐文章于 2021-11-04 23:13:57 发布