JAVA IO流RandomAccessFile随机读取

<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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值