什么是IO
输入输出流,使用数据通讯的通道。
File
java代码是可以操作硬盘上的文件的,因为硬盘上文件可以映射为java内存中的File,我们直接操作内存中的File,就可以间接的操作硬盘上的文件。
IO分类
输入\输出 字节\字符
- 字节输入流
- 字节输出流
- 字符输入流
- 字符输出流
图片的复制
/*
* 字节流
*
* 目标:复制一个图片到另外一个地方。
* 流都是占资源的,需要释放。
*/
// 先创建目标文件
FileInputStream fis = null ;
FileOutputStream fos = null ;
try {
File target = new File("d://b/b.png");
if(!target.exists()){
target.createNewFile();
}
// 创建我们需要的流,输入字节流 XXInputStream
File src = new File("d://a/a.png");
// 输入流,用来读取原目标的数据
fis = new FileInputStream(src) ;
fos = new FileOutputStream(target);
byte [] b = new byte [1024] ;
int i = -1 ;
while((i = fis.read(b))!= -1){// 读取数据放入b中。返回结果是读取多少有效数据。
System.out.println(i);
// 把每次读取到的数据通过输出流写到目标文件中
fos.write(b, 0, i);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
// 释放资源
try {
if(fis != null){
fis.close();
}
if(fos != null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
文本文件的读取
/*
* 字符:
* 读取这个txt文件中的所有的内容,并在控制台打印
*
*/
FileReader fr = null ;// 建立输入流
BufferedReader br = null ;// 建立输入流的包装流
try {
File file = new File("d://a/a.txt");
fr = new FileReader(file);
br = new BufferedReader(fr);
String s = null ;
// 循环读取文件中的内容,并打印在控制台中
while((s = br.readLine() ) != null){
System.out.println(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
// 2层流,需要先关外面的,再关里面的
try {
if(br!=null){
br.close();
}
if(fr!=null){
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
文本文件的写入
File file = new File("d://a/b.txt");
FileWriter fw = null ;//建立输出流
BufferedWriter bw = null ;//在输出流上建立包装流
try {
fw = new FileWriter(file,true);// false是覆盖,默认; true:追加
bw = new BufferedWriter(fw);
bw.write("你好啊333,今天星期五了,\n");// 往流里面写内容
bw.write("马上要周末了。");
bw.newLine();// 换行
bw.write("明天开始旅游免费。");
bw.newLine();
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
// 关闭流
try {
if(bw!=null){
bw.close();
}
if(fw!=null){
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
特定变量
public static void main(String[] args) throws IOException {
File file = new File("d://a/a.txt");
try(
//定义一些特定变量,变量必须实现一个Closeable接口
FileReader fr = new FileReader(file) ;
BufferedReader br = new BufferedReader(fr);
){
String s = null ;
while((s = br.readLine() ) != null){
System.out.println(s);
}
}
//不需要关系流的关闭,会自动的调用流的close方法,这也是为什么try中的变量需要实现Closeable接口
}