IO流学习笔记
数据的交互需要有一个媒介或者管道,把这个媒介或者管道就称为IO流,也被称为输入输出流
1.1字节输入流
InputStream是一个抽象类,不能实例化对象。
方法名 | 描述 |
---|
void close() | 关闭此输入流并释放与该流关联的所有系统资源。 |
int read() | 从输入流中读取数据的下一个字节。 |
int read(byte[] b) | 从输入流中读取一定数量的字节,并将其存储在缓冲区数组b中。 |
int read(byte[] b,int off, int len) | 将输入流中最多len个数据字节读入 byte 数组。 |
1.2文件输入流FileInputStream
public static void main(String[] args) throws Exception{
FileInputStream fis=new FileInputStream("d:\\aaa.txt");
System.out.println("可读取字节个数:"+fis.available());
byte[] buf=new byte[10];
int len=0;
while((len=fis.read(buf))!=-1) {
for(int i=0;i<len;i++) {
System.out.print((char)buf[i]);
}
}
fis.close();
}
2.1字节输出流OutputStream
OutputStream是抽象类,不能实例化对象。
方法名 | 描述 |
---|
void close() | 关闭此输出流并释放与此流有关的所有系统资源。 |
void flush() | 刷新此输出流并强制写出所有缓冲的输出字节。 |
void write(byte[] b) | 将 b.length 个字节从指定的 byte 数组写入此输出流。 |
void write(byte[] b,int off, int len) | 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。 |
void write(int b) | 将指定的字节写入此输出流。 |
public class TestFileOutputStream {
public static void main(String[] args) {
File file = new File("test\\hello.txt");
FileOutputStream fos = null;
try {
fos=new FileOutputStream(file, true);
String str = "hello world";
byte[] b = str.getBytes();
System.out.println(b.length);
fos.write(b);
}catch(IOException e) {
e.printStackTrace();
} finally {
if(fos!=null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
3.1字符输入流reader类
Reader:是所有字符输入流的父类,为一个抽象类,不能实例化对象,使用它的子类FileReader类
public static void main(String[] args) throws Exception{
Reader reader=new FileReader("g:\\book.txt");
char[] arr = new char[1024];
//4.定义一个int的变量 int hasRead = 0;
//5.循环读取
while((hasRead = reader.read(arr)) != -1) {
String result = new String(arr, 0, hasRead);
System.out.println(result);
}
}
4.1字符输出流writer类
Writer:是所有字符输出流的父类,为一个抽象类,不能实例化对象,使用它的子类FileWriter类
public class FileWriterUsageDemo {
public static void main(String[] args) throws IOException {
File file = new File("file/output1.txt");
Writer writer = new FileWriter(file);
writer.write("天边最美的云彩");
writer.flush();
writer.close();
}
}
案例练习
1使用字节流复制文件
边读边写
public static void copy1() throws Exception{
InputStream is=new FileInputStream("g:\\book.txt");
OutputStream os=new FileOutputStream("g:\\copyNewbook.txt");
byte[] buf=new byte[1024*4];
int len=0;
while((len=is.read(buf))!=-1){
os.write(buf,0,len);
}
is.close();
os.close();
System.out.println("复制完成");
}
2使用字符流复制文件
public static void copy2() throws Exception{
Reader reader=new FileReader("g:\\book.txt");
Writer writer=new FileWriter("g:\\newBook");
char[] buf=new char[1024*4];
int len=0;
while((len=reader.read(buf))!=-1){
writer.write(buf, 0, len);
}
reader.close();
writer.close();
System.out.println("复制完成");
}
如果复制的文件是文本文件 ,用字节流和字符流都可以
如果复制的文件是图片、音乐、电影, 用字符流复制会出现问题. 使用字节流.