1.IO流按数据类型分为:字节流和字符流
2.使用:
如果数据可通过Windows自带的记事本软件打开并且不乱码,就使用字符流;否则使用字节流;如果不知道使用哪种就使用字节流。
3.字节流写数据与异常捕获
FileOutputStream fileOutputStream = null;
try {
//刷新写入数据
// fileOutputStream = new FileOutputStream("/Users/fuguangwu/itcast/test.txt");
//true代表追加写入数据
fileOutputStream = new FileOutputStream("/Users/fuguangwu/itcast/test.txt", true);
for (int i = 0; i < 10; i++) {
fileOutputStream.write("hello".getBytes());
//换行符 windows:"\r\rn" linux:"\n" mac:"\r"
fileOutputStream.write("\r".getBytes());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
//释放资源
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.字节流读数据(一次读一个字节数组数据)
//创建字符输入流对象
FileInputStream fileInputStream = new FileInputStream("/Users/fuguangwu/itcast/test.txt");
byte[] bytes = new byte[1024]; //2014的整数倍
int len;
while ((len = fileInputStream.read(bytes)) != -1) {
System.out.println(new String(bytes, 0, len));
}
//释放资源
fileInputStream.close();
5.复制文本文件
//创建字符输出流对象
FileOutputStream fileOutputStream = new FileOutputStream("/Users/fuguangwu/itcast/test1.txt");
//创建字符输入流对象
FileInputStream fileInputStream = new FileInputStream("/Users/fuguangwu/itcast/test.txt");
byte[] bytes = new byte[1024]; //2014的整数倍
int len;
while ((len = fileInputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes,0,len);
}
//释放资源
fileInputStream.close();
fileOutputStream.close();
6.字节缓冲流
- BufferedOutPutStream:
该类实现缓冲输出流。通过设置这样的输出流,应用程序可以向底层输出流写入字符,而不必为写入的每个字节导致底层系统的调用。
- BufferedInputStream:
创建BufferedInputStream将创建一个内部缓冲区数组。当从流中读取或跳过字节时,内部缓冲区将根据需要从所包含的输入流中重新填充,一次很多字节。
-构造方法:
字节缓冲输出流:BufferedOutputStream(OutputStream out)
字节缓冲输入流:BufferedInputStream(InputStream in)
-为什么构造方法需要的是字节流,而不是具体的文件或者路径呢?
字节缓冲流仅仅提供缓冲区,而真正的读写数据还是要依靠基本的字节流对象进行操作
7.举例
//创建字符输出流对象
// FileOutputStream fileOutputStream = new FileOutputStream("/Users/fuguangwu/itcast/test1.txt");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("/Users/fuguangwu/itcast/test1.txt"));
//创建字符输入流对象
// FileInputStream fileInputStream = new FileInputStream("/Users/fuguangwu/itcast/test.txt");
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("/Users/fuguangwu/itcast/test.txt"));
byte[] bytes = new byte[1024]; //2014的整数倍
int len;
while ((len = bufferedInputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, len);
}
//释放资源
bufferedInputStream.close();
bufferedOutputStream.close();