IO 工具类

第一种,将二进制数组写入文件中

传入二进制数组(byteArr)和文件路径(dataPath)

public static void writeDataFile(byte [] byteArr,String dataPath){
		OutputStream os =null;
		try {
			os = new FileOutputStream(dataPath,true);//第二個参数为true表示程序每次运行都是追加字符串在原有的字符上
			os.write(byteArr);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			CloseUtil.close(os);
		}
	}

第二种,将字符串写入文件

传入字符串(str)和文件路径(indexPath)

public static void writeIndexFile(String str,String indexPath){
		PrintWriter out=null;
		try {
		out = new PrintWriter(new FileOutputStream(indexPath,true));
		out.println(str);
		} catch (Exception e) {

			e.printStackTrace();
		}finally{
			CloseUtil.close(out);
		}
		
	}

第三种,根据偏移量和文件大小查找文件内容并且输出

传入偏移量(pos),文件大小(size),文件路径(dataPath),字符集编码(encoding)

返回 所找到内容的String形式

 

public static String readDataFile(long pos, int size, String dataPath,
			String encoding) {
		String result = "";	
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(dataPath, "r");//r表示读  w表示写
			raf.seek(pos);//表示将指针指向偏移量pos处
			byte[] b = new byte[size];
			raf.read(b);//传入从指针开始需要读取的内容大小
			result = new String(b, encoding);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			CloseUtil.close(raf);
		}
		return result;
	}

这里用了一个RandomAccessFile类

这个类是Java提供的对文件内容的访问,可读可写,可访问文件的任意位置

注意:此类需要关闭!!!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值