IO流
1. 概念
- IO流用来处理设备之间的数据传输
- java 对数据的操作都是流的方式
- java 操作流的类在IO包中
- 流按流向分类 输入流, 输出流
- 流按操作类型分类:
1. 字节流: 字节流可以操作任何数据, 因为计算机中任何数据都是已字节存储的
2. 字符流: 字符流只能操作纯字符数据, 比较方便
2. IO流常用父类
- 字节流的抽象父类
- InputStream
- OutputStream
TIP
read() 方法读取的是一个字节, 为什么返回是int 而不是byte 因为文件底层都事二进制存储的, 如果每次读取返回byte, 有可能读取到 11111111 , 这是byte类型的-1 程序遇到-1停止了.
字符流的抽象父类
- Reader
- Writer
IO程序书写
- 使用前 导入IO包中类
- 使用时 进行IO异常处理
- 使用后 释放资源
字节流 读写中文
字节流读取 中文会造成乱码, 因为一次读取一个字节
字节流写出 必须转换成字节数组 getBytes()
测试
- 输入路径复制文件
public class CopyFile {
public static void main(String[] args) throws IOException {
File file = getFile();
BufferedInputStream bif = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bof = new BufferedOutputStream(new FileOutputStream(file.getName()));
int d;
while ((d = bif.read()) != -1){
bof.write(d);
}
bif.close();
bof.close();
}
public static File getFile(){
System.out.println("请输入一个路径");
Scanner sc = new Scanner(System.in);
String path = sc.nextLine();
File file = new File(path);
while (true){
if(!file.exists()){
System.out.println("路径不存在, 请重新输入");
}else if(file.isDirectory()){
System.out.println("您输入的是文件夹路径, 请重新输入");
}else {
return file;
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
图片加密解密
public class Img {
public static void main(String[] args) throws IOException {
BufferedInputStream bif = new BufferedInputStream(new FileInputStream("C:\\Users\\Administrator\\Desktop\\12.jpg"));
BufferedOutputStream bof = new BufferedOutputStream(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\3.jpg"));
int b;
while ((b = bif.read()) != -1){
bof.write(b ^ 123);
}
bif.close();
bof.close();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12