java中流的分类
1.按数据流的方法不同可以分为输入流和输出流
2.按处理数据单位的不同可以分为字节流和字符流
3.按功能的不同可以分为节点流和处理流
JDK所提供的所有流类型位于java.io内分别继承自一下四种抽象流类型
字节流 | 字符流 | |
---|---|---|
输入流 | InputStream | Reader |
输出流 | OutputStream | Writer |
字节流
一个字节一个字节的读写
1.FileInputStream
FileInputStream in = null;
int b =0;
try {
in = new FileInputStream("f:\\test.txt");
} catch (FileNotFoundException e) {
System.out.print("文件找不到");
e.printStackTrace();
}
try {
while ((b =in.read()) != -1){
System.out.print((char)b);//这么转汉字(因为汉子是2个字节)会出错
}
in.close();
} catch (IOException e) {
System.out.println("文件读取错误");
e.printStackTrace();
}
2.FileOutputStream
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream("f:\\test.txt");
out = new FileOutputStream("f:\\copyTest.txt");
} catch (FileNotFoundException e) {
System.out.print("文件找不到");
e.printStackTrace();
}
try {
while ((b =in.read()) != -1){
out.write(b);
}
in.close();
out.close();
} catch (IOException e) {
System.out.println("文件复制完成");
e.printStackTrace();
}
字符流
一个字符一个字符的读写
1.FileReader
Reader read = null;
int b =0;
try {
read = new FileReader("f:\\test.txt");
} catch (FileNotFoundException e) {
System.out.print("文件找不到");
}
try {
while ((b =read.read()) != -1){
System.out.print((char)b);
}
read.close();
} catch (IOException e) {
e.printStackTrace();
}
2.FileWriter
Reader read = null;
Writer writer = null;
int b = 0;
try {
read = new FileReader("f:\\test.txt");
writer = new FileWriter("f:\\writerCopy");
} catch (FileNotFoundException e) {
System.out.print("文件找不到");
}
try {
while ((b =read.read()) != -1){
writer.write(b);
}
read.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}