I/O流实例

package com.fs.test;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;

import javax.imageio.ImageTypeSpecifier;

public class StreamTest {
	public static void main(String[] args) throws IOException {
		File file = new File("test.txt");

//		read(file);
//
//		write(file);
		int len = (int) file.length();
		
		byte[] data = readData(file, len, 200, len / 200 + 1);
		System.out.println(new String(data));
	}

	private static void write(File file) throws FileNotFoundException, IOException {
		// 写入文本
		FileOutputStream out = new FileOutputStream(file, true);
		String str = "哈哈哈";
		byte[] b2 = str.getBytes();
		out.write(b2, 0, b2.length);
		out.close();
	}

	private static void read(File file) throws FileNotFoundException, IOException {
		// 读取
		FileInputStream in = new FileInputStream(file);
		int length = (int) file.length();
		System.out.println(length);
		byte[] b = new byte[length];
		// int a = in.read(b, 0, length);
		// read方法 尝试着读取len个字节到byte[]数组中 off:表示存的时候偏移多少个字节
		int a2 = in.read(b, 6, length - 6);
		System.out.println(new String(b));
		in.close();
	}
	
	/**
	 * 
	 * @param bin 输入流
	 * @param size 文件的大小 100
	 * @param max 每次  【 尝试 】  读取的最大字节数 9
	 * @param count 尝试读取的次数,如果读取次数用完,直接不读了
	 * @return
	 * @throws FileNotFoundException 
	 */
	public static byte[] readData(File file, int size, int max, int count) throws FileNotFoundException {
		BufferedInputStream bin = new BufferedInputStream(new FileInputStream(file));
		// 装数据的数组
		byte[] data = new byte[size];
		// 已经读取的字节数
		int hasRead = 0;
		// 只要还没有读完,就一直读
		while (true) {
			count--;
			// 当没读完的字节数少于设定字节数时,
			// 就尝试着读 没读完的字节数
			if (max > size - hasRead) {
				max = size - hasRead;
			}
			try {
				// 读一次就更新一次已读字节数
				hasRead = hasRead + bin.read(data, hasRead, max);
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 读完就跳出循环
			if (hasRead == size || count == 0) {
				break;
			}
		}
		return data;
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值