IO流的分类:
流向:输入流 输出流
单位: 字节流 字符流
字节输入流 字节输出流 字符输入流 字符输出流
InputStream OutputStream
使用字节输出流来实现写出数据;
FileOutputStream
换行写 追加写 异常处理
使用字节输入流来读数据:
FileInputStream
实现文件的复制
/*
将D:\\IO\os\\窗里窗外.txt文档复制到当前module中
*/
public class FileCopy {
public static void main(String[] args) throws IOException {
// 实现读数据
FileInputStream fis = new FileInputStream("D:\\IO\\os\\窗里窗外.txt");
// 实现写数据
FileOutputStream fos = new FileOutputStream("day_11_IODemo\\copy\\窗里窗外.txt");
// 使用输入流来读数据 每次读取一个字节 读完之后 立即使用输出流将数据写出到目标文件
int len;
long begin = System.currentTimeMillis();// 获取开始 复制的时间
while((len = fis.read()) != -1){
fos.write(len);
}
long end = System.currentTimeMillis();
System.out.println("复制文件完成,共耗时:" + (end - begin) + "毫秒");//复制文件完成,共耗时:2189毫秒
// 释放资源
fos.close();
fis.close();
}
}
使用字节流读取数据(每次读取一个字节数组)
public class FileReadByteArray {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("D:\\IO\\os\\fos.txt");
// int read(byte[] b)
byte[] buff = new byte[10];
int len;
while( (len =fis.read(buff)) != -1){//每次读取10个字节 在去输出
// 将读取到的字节数组转换为字符串 输出
System.out.println(new String(buff));
}
fis.close();
}
\n w o r l d l l o \r
解决方法
String(byte[] bytes, int offset, int length)
通过使用平台的默认字符集解码指定的字节子阵列来构造新的 String 。
public class FileReadByteArray {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("D:\\IO\\os\\fos.txt");
// int read(byte[] b)
byte[] buff = new byte[10];
int len;
while( (len =fis.read(buff)) != -1){//每次读取10个字节 在去输出
// 将读取到的字节数组转换为字符串 输出转换的时候 读几个就转换几个
System.out.print(new String(buff,0,len));//
}
fis.close();
}
}
使用每次读取一个字节数组的方式 实现文件的复制
/**
* @author Mr.Hu
* @create 2021/01/13
*
* 将D:\\IO\os\\窗里窗外.txt文档复制到当前module中 采用读取一个字节数组的方式
*
*/
public class FileCopyByByteArray {
public static void main(String[] args) throws IOException {
FileInputStream fis= new FileInputStream("d:\\IO\\os\\窗里窗外.txt");
FileOutputStream fos = new FileOutputStream("day_11_IODemo\\copy\\copy.txt");
byte[] buff = new byte[1024];
int len;
long begin= System.currentTimeMillis();
while((len = fis.read(buff))!= -1){
fos.write(buff,0,len);
}
long end = System.currentTimeMillis();
System.out.println("复制文件完成,共耗时:" + (end - begin) + "毫秒");
fos.close();
fis.close();
}
使用每次读取一个字节数组的方式 实现图片的复制
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("D:\\IO\\os\\fos.txt");
// int read(byte[] b)
byte[] buff = new byte[10];
int len;
while( (len =fis.read(buff)) != -1){//每次读取10个字节 在去输出
// 将读取到的字节数组转换为字符串 输出转换的时候 读几个就转换几个
System.out.print(new String(buff,0,len));//
}
fis.close();
}