什么是IO流
I:是从外部设备到应用程序之间的数据传递,常见的外部设备包括文件、管道、网络连接
O:是从应用程序到外部设备的数据传递
分类
按流向分为,输入流,输出流
按处理数据单位:字节流、字符流
字节流的应用
public class TestStream {
public static void main(String[] args) throws IOException {
File file = new File("E:\\MultiMediaOpt\\Test\\TestIO1.txt");
OutputStream os = new FileOutputStream(file, true);
// 要写入的字符串
String string1 = "采菊东篱下,悠然见南山";
// 写入文件
os.write(string1.getBytes());
// 关闭流
os.close();
InputStream in = new FileInputStream(file);
// 一次性取多少个字节
byte[] bytes = new byte[1024];
// 用来接收读取的字节数组
// 读取到的字节数组长度,为-1时表示没有数据
int length = 0;
length = in.read(bytes);
String string = new String(bytes,0,length);
in.close();
// 关闭流
System.out.println(string);
}
}
缓冲流的应用
public class TestStream{
public static void main(String[] args) throws IOException {
File file = new File("E:\\MultiMediaOpt\\Test\\TestIO1.txt");
OutputStream os = new FileOutputStream(file);
BufferedOutputStream out = new BufferedOutputStream(os);
// 要写入的字符串
String string1 = "采菊东篱下,悠然见南山";
// 写入文件
out.write(string1.getBytes());
out.flush();
InputStream inputStream = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(inputStream);
// 一次性取多少个字节
byte[] bytes = new byte[1024];
// 用来接收读取的字节数组
// 读取到的字节数组长度,为-1时表示没有数据
int length = 0;
StringBuilder string = new StringBuilder();
while((length = in.read(bytes))!=-1){
string.append(new String(bytes, 0, length));
}
in.close();
os.close();
// 关闭流
System.out.println(string);
}
}