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提供的对文件内容的访问,可读可写,可访问文件的任意位置

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

 

你可能感兴趣的:(自用,工具类,Java,IO,工具类,写文件和查找文件内容)