什么是IO流
流(Stream):源于UNIX中管道(pipe)的概念。在UNIX中,管道是一条不间断的字节流,用来实现程序或进程间的通信,或读写外围设备,外部文件等。
IO流分为几类
两类:字节流和字符流
什么是字节流?什么是字符流?
字节流的概念:字节流是由字节组成的,字节流是最基本的,所有的InputStream和OutputStream的子类都是字节流,主要用在处理二进制数据,它是按字节来处理的。
字符流的概念:字符流是由字符组成的,Java里字符由两个字节组成,所有的Reader和Writer的子类都是字符流,主要用在处理文本内容或特定字符。
字节流和字符流的区别
字节流操作的基本单元为字节;字符流操作的基本单元为Unicode码元。
字节流默认不使用缓冲区;字符流使用缓冲区。
字节流通常用于处理二进制数据,实际上它可以处理任意类型的数据,但它不支持直接写入或读取Unicode码元;字符流通常处理文本数据,它支持写入及读取Unicode码元。
字符流的常用类有哪些
Reader:BufferedReader;
InputStreamReader;
FileReader;
Write:BufferedWriter;
OutputStreamWriter;
FileWriter;
实现文件复制的思路和步骤是什么
public class Ex3 {
public static void main(String[] args) {
FileInputStream input = null;
FileOutputStream output = null;
int n = 0;
try {
input = new FileInputStream("D:\\Lenovo\\info.txt");
output = new FileOutputStream("D:\\Lenovo\\info1.txt");
do {
n = input.read();
output.write(n);
}while (n!=-1);
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
input.close();
output.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
如何使用字符流进行文件读写
public class Test {
public static void main(String[] args) {
int count = 0;
FileReader reader = null;
BufferedReader breader =null;
BufferedWriter writer = null;
try {
reader = new FileReader("D:\\Lenovo\\inof.txt");
writer = new BufferedWriter(new FileWriter("D:\\Lenovo\\info.txt"));
breader = new BufferedReader(reader);
String temp ="";
while((temp=breader.readLine())!=null){
writer.write(temp);
writer.newLine();
}
writer.flush();
System.out.println("共循环"+count+"次");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
breader.close();
reader.close();
writer.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}