字节流---输入输出

时间:2022-07-22
本文章向大家介绍字节流---输入输出,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

流的输入及输出均是对程序而言

字节流输入

  1. 创建File对象,关联文件
File src = new File("D:/aa", "a.txt");
  1. 1)、创建以src为输入流的对象,
Inputstream in = new FileInputStream(src);
  1. 2)、建立字节数组(byte[]),创建长度整形变量len
byte[] car = new byte[10];
int len = 0;
  1. 3)、读取输入流,将byte[]转换为String并输出
while (-1 != (len = in.read(car))) {
	String info = new String(car, 0, len);
	System.out.println(info);
}

read()返回读入长度,为-1时结束

2. 4)、读取结束后关闭输入流

in.close();
  1. 进行异常处理
try {
	in = new FileInputStream(src);
	byte[] car = new byte[10];
	int len = 0;
	while (-1 != (len = in.read(car))) {
		String info = new String(car, 0, len);
		System.out.println(info);
	}
} catch (FileNotFoundException e) {
	System.out.println("文件读取失败");
} catch (IOException e) {
	System.out.println("文件流操作失败");
} finally {
	if (in != null) {
		try {
			in.close();
		} catch (IOException e) {
			System.out.println("关闭输入流失败");
		}
	}
}

字节流输出

  1. 创建File对象,关联文件
File src = new File("D:/aa", "a.txt");
  1. 1)、创建以src为输出流的对象,
Outputstream in = new FileOutputStream(src);
  1. 2)、建立字符串,转换为字节数组并写入
String str = "simplen";
out.write(str.getBytes());
  1. 3)、刷新输出流
out.flush();

flush()方法使流中的数据写入文件

2. 4)、读取结束后关闭输出流

out.close();
  1. 进行异常处理
try {
	out = new FileOutputStream(src, true);
	String str = "simplen";
	out.write(str.getBytes());
	out.flush();
} catch (FileNotFoundException e) {
	System.out.println("文件不存在");
} catch (IOException e) {
	System.out.println("文件流操作失败");
} finally {
	if (out != null) {
		try {
			out.close();
		} catch (IOException e) {
			System.out.println("关闭输出流失败");
		}
	}
}

完整代码(输入):

package cn.hxh.io.filebyte;

import java.io.*;

public class myInputStream {

	public static void main(String[] args) {
		File src = new File("D:/aa", "a.txt");
		InputStream in = null;
		try {
			in = new FileInputStream(src);
			byte[] car = new byte[10];
			int len = 0;
			while (-1 != (len = in.read(car))) {
				String info = new String(car, 0, len);
				System.out.println(info);
			}
		} catch (FileNotFoundException e) {
			System.out.println("文件读取失败");
		} catch (IOException e) {
			System.out.println("文件流操作失败");
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					System.out.println("关闭输入流失败");
				}
			}
		}
	}

}

完整代码(输出):

package cn.hxh.io.filebyte;

import java.io.*;

public class myOutputStream {

	public static void main(String[] args) {
		File src = new File("D:/aa", "a.txt");
		OutputStream out = null;
		try {
			out = new FileOutputStream(src, true);
			String str = "simplen";
			out.write(str.getBytes());
			out.flush();
		} catch (FileNotFoundException e) {
			System.out.println("文件不存在");
		} catch (IOException e) {
			System.out.println("文件流操作失败");
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					System.out.println("关闭输出流失败");
				}
			}
		}
	}

}