IO流分类:
流向:
输入流
输出流
数据类型:
1.字节流
字节输入流
字节输出流
2.字符流
字符输入流
字符输出流
字节输入流:
具体操作步骤:
字节输入流操作步骤:
A:创建字节输入流对象
FileInputStream fis = new FileInputStream(“a.txt”);
B:调用方法读取数据
一次读取一个字节:read()
C:释放资源
fis.close
& FileOutputStream fos = new FileOutputStream(“fos.txt”);
请问上面这个操作做了哪几件事情?
1.创建了一个文件输出流fos,指向文件a.txt
2.创建了a.txt这个文件
输出演示:
public class OutputStreamExercise {
/**
* 需求:请用字节流往一个文本文件中写一句话:"helloworld"。
* @throws IOException
*/
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("a.txt");
//调用输出流的写数据的方法给文件中写数据
String s="helloworld";
byte[] bs = s.getBytes();
fos.write(bs);
//释放资源,关流操作
fos.close();
}
输入演示:
public class InputStreamExercise {
/**
* A:创建字节输入流对象
FileInputStream fis = new FileInputStream("a.txt");
* B:调用方法读取数据
一次读取一个字节:read()
* C:释放资源
fis.close
* @throws IOException
*/
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("a.txt");
int a;
while((a=fis.read())!=-1){
System.out.println((char)a);
}
fis.close();
}
}
练习:复制一个图片文件
public class CopyExercise {
/**
* 复制一个图片
* @throws IOException
*/
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("E://KanKan//W020080220354931747530.jpg");
FileOutputStream fos = new FileOutputStream("c.jpg");
//一次读写一个字节数组
byte[] bys = new byte[1024];
int len;
while((len=fis.read(bys))!=-1){
fos.write(bys, 0, len);
}
fis.close();
fos.close();
}