JAVA IO流RandomAccessFile随机读取

来源:互联网 发布:不是淘宝卖家能贷款吗 编辑:程序博客网 时间:2024/05/18 00:59
<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);}}



0 0
原创粉丝点击