IO分类理解
输入、输出流的分类
从程序角度看待输入和输出
字节流:一个字节(8位)一个字节往外读
字符流:一个字符一个字符往外读
字符是2个字节
节点流:一个特定的数据源(节点)读写数据 (如:文件、内存)
处理流:套在其他管道上面的流,叫处理流
字节流
InputStream继承类
InputStream基本使用方法
OutputStream继承类
OutputStream基本使用方法
package com.stream;
import java.io.*;
/**
* 字节流
*/
public class InputStreamDemo {
public static void main(String[] args) {
InputStreamDemo inputStreamDemo = new InputStreamDemo();
inputStreamDemo.inputStreamWithByte();
}
//字节流操作,一个字节一个字节的读取
private void inputStream(){
String fileName = "aaa.txt";
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(fileName);
outputStream = new FileOutputStream(fileName);
outputStream.write("12sadbd".getBytes());
outputStream.flush();
int read = 0;
while ( (read =inputStream.read()) != -1){
System.out.print((char)read);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//字节流,使用bytes数组读取
private void inputStreamWithByte(){
String fileName = "aaa.txt";
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(fileName);
byte[] bytes = new byte[1];
outputStream = new FileOutputStream(fileName);
outputStream.write("12sadbd".getBytes());
outputStream.flush();
while(inputStream.read(bytes)!= -1){
System.out.print(new String(bytes));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}