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;
}
}
I/O流实例
最新推荐文章于 2021-02-19 23:55:54 发布