第十八天学习笔记

本文详细介绍了Java中关于输入流(如FileInputStream和BufferedReader)、输出流(如FileOutputStream和FileWriter)的使用,包括纯文本文件的读写、字符集编码解码、文件拷贝、小文件加速拷贝、异常处理以及压缩解压缩流的应用实例。
摘要由CSDN通过智能技术生成

Io流:创建输入流要小心点,因为一旦被创建,则内容会被删除

1.基本知识点

纯文本文件:可以用Ascall码表示的文本数据

2.分类

3.输出流

代码实现:

//生成要传输的文件通道
OutputStream outputStream = new FileOutputStream("D:\\JavaStudyDir\\a.txt");
//传输文件
byte[] bytes = {'a','b','c'};   //byte[],不要写成包装类,这里识别不出来。
outputStream.write(bytes);   //写文件的时候会覆盖原有的内容
//关闭通道
outputStream.close();

代码实现的细节

代码实现:

public static void main(String[] args) throws IOException {
    //生成要传输的文件通道
    OutputStream outputStream = new FileOutputStream("D:\\JavaStudyDir\\a.txt",true);
(把append开关打开以后就能不清楚原有文件内容接着写东西,把创建文件后面的内容改成true就行)
    //传输文件
    byte[] bytesOne = {'a','b','c'};   //byte[],不要写成包装类,这里识别不出来。
    outputStream.write(bytesOne);   //写文件的时候会覆盖原有的内容

    //换行输出需要用  \r\n
    String str = " \r\n";(这是换行符,在这里不需要用转义字符,因为字符串中内容不会更改)
    byte[] bytesLine = str.getBytes();
    outputStream.write(bytesLine);

    //在创建的文件中接着写
    byte[] bytesTwo = {'a','b','c'};   //byte[],不要写成包装类,这里识别不出来。
    outputStream.write(bytesTwo);   //写文件的时候会覆盖原有的内容
    //关闭通道
    outputStream.close();


}

4.输入流

知识点

代码:
//读文件操作
//生成通道
FileInputStream  fis= new FileInputStream("D:\\JavaStudyDir\\a.txt");
//阅读数据,返回int类型数据
int num =  fis.read();  //fis.read()  读取当前字符并移动至下一个字符
//打印
System.out.println(num);
//关闭通道
fis.close();

循环读取:

//生成通道
  FileInputStream  fisTwo= new FileInputStream("D:\\JavaStudyDir\\a.txt");
  int b =0;//创建第三方变量记录当前数据,防止二次调用会读取错误。
  //阅读数据,返回int类型数据
while((b=fisTwo.read())!=-1){
    System.out.println(b);
}      //fis.read()  读取当前字符并移动至下一个字符

  //关闭通道
  fisTwo.close();

5.文件拷贝(小文件),找到文件创建对应类型的文件夹即可

加速版:

//文件拷贝 可以拷贝小文件,包括视频,速度加快版
//这两个输入输出顺序不要搞反了
FileInputStream fis =  new FileInputStream("D:\\JavaStudyDir\\aaa\\bbb\\ccc\\Test.mp4"); 
FileOutputStream fos = new FileOutputStream("D:\\JavaStudyDir\\niuniu.mp4");
//定义一个数,接收fis.read()的数值,看下一轮读了几个字节
int b =0;
//这里为了让他多跑一会  每次读10K
byte[] bytes = new byte[1024*10];   
//当一直有数的存在即可以读
while((b = fis.read(bytes))!= -1){
    //这里要限制一下输入,因为末尾没有数据读是不会重新刷新数组的
    //这里要写入0到读入的长度,这样就可以完整输入
    fos.write(bytes,0,b);
}
//先打开先关闭
fos.close();
fis.close();

6.异常Try Catch再学习

6.字符集(Ascall,GBK):

了解即可:

7.编码和解码

代码:

//编码和解码的代码演示

 //ava中编码的方法
 //public byte[ ] getBytes()        使用默认方式进行编码
 //public byte[] getBytes(String charsetName)        使用指定方式进行编码

 //ava中解码的方法
 // String( byte[] bytes)   使用默认方式进行解码
 //String(byte[] bytes, String charsetName)     使用指定方式进行解码

String str1 = "tan个恋爱吧";
 byte[] bytes = str1.getBytes();
 System.out.println(Arrays.toString(bytes));
 byte[] bytesTwo = str1.getBytes("UTF-8");
 System.out.println(Arrays.toString(bytesTwo));

 String str2 = new String(bytes);
 String str3 = new String(bytes,"UTF-8");
 System.out.println(str2);
 System.out.println(str3);

8.字符流输入

细节:要注意

//字符流代码实现
int b=0;
FileReader fr = new FileReader("D:\\JavaStudyDir\\a.txt");
while ((b=fr.read())!=-1){
    System.out.print((char) b);
}
fr.close();

9.字符流和字节流细节

在文本文档中,只要换行了,文字末尾自带   \r\n  ,我们看不见,但是用代码扫描可以扫出来并且打印。

10.字符流输出

11.文件拷贝:为考虑通用性,一般会使用字节流

类中代码实现:

//文件拷贝

File srcFile = new File("D:\\JavaStudyDir");
File  aimFile= new File("D:\\JavaStudyDirTwo");
//一次读1024 B文件
copyDir(srcFile,aimFile);

方法:

public  static void  copyDir(File srcFile,File aimFile) throws IOException {
    aimFile.mkdirs();  //如果没有就创建这个文件夹,有的话就不创建  mkdirs:创建多级文件夹
    int len=0;   //接受复制数组的长度
    File[] files = srcFile.listFiles(); //遍历文件夹
    if(files !=null){   //防止扫到不存在,路径名,有权限的文件。
    for (File file : files) {
        if(file.isFile()) {
            File tempFile = new File(aimFile+ "\\" + file.getName()); //创建文件,方便接收数据
            FileInputStream fis = new FileInputStream(file);  //扫面当前文件
            FileOutputStream fos = new FileOutputStream(tempFile);  //写入刚创建的文件
            while ((len = fis.read(bytes))!= -1) {   //扫描
                fos.write(bytes,0,len);
            }
            fis.close();
            fos.close();
            }
        else {
            //是文件的话就递归调用。
           copyDir(file,new File(aimFile+"\\"+file.getName()));
        }
      }
    }
}

12.文件加密练习:异或运算

 //为了保证文件的安全性,就需要对原始文件进行加密存储,再使用的时候再对其进行解密处理。
 //加密原理:对原始文件中的每一个字节数据进行更改,然后将更改以后的数据存储到新的文件中。
 //解密原理:读取加密之后的文件,按照加密的规则反向操作,变成原始文件
 //这里可以用到^ ,两个相同则为false     
 //加密代码如下,解密过程是  让加密文件再与初始数字再进行一次^运算。
 File fileOne = new File("D:\\JavaStudyDir\\a.txt");
 FileInputStream fis = new FileInputStream(fileOne);
 File fileTwo = new File("D:\\JavaStudyDir\\c.txt");
 FileOutputStream fos = new FileOutputStream(fileTwo);
 int len = 0;
 while((len=fis.read())!=-1){
     fos.write(len^2);
 }
 fos.close();
 fis.close();

13.缓冲流分类:

//缓冲流
BufferedReader bufferedReader = new BufferedReader( new FileReader("D:JavaStudyDir\\a.txt"));
String str=null;

while ((str = bufferedReader.readLine() )!=  null){
System.out.println(str);

}
bufferedReader.close();

14.转换流:通过字节流读取文本可以通过转换流去指定编码生成新文件,否则读取不了,会乱码。

JDK11:之后的文本

InputStreamReader isr= new InputStreamReader(new FileInputStream("D:\\JavaStudyDir\\cgbk.txt"),"GBK");
//只能读取gbk文件,因为指定了读取的编码,否则乱码。
int numFlag ;
while ((numFlag = isr.read())!=-1){
    System.out.println((char) numFlag);
}

isr.close();

JDK11在后的可以在Filereader中定义

FileReader isrTwo = new FileReader("D:\\JavaStudyDir\\cgbk.txt"),CharSet.forname("GBK"));
//只能读取gbk文件,因为指定了读取的编码,否则乱码。
int numFlagTwo ;
while ((numFlagTwo = isr.read())!=-1){
    System.out.println((char) numFlag);
}

isr.close();

15.转换流练习

//读取GBK文件转换UTF-8文件     虽然读的字节不同,但是通过这两个包装方法后,会自动根据编码生成,很牛逼
// 1.JDK11以前的方案
InputStreamReader isr= new InputStreamReader(new FileInputStream("D:\\JavaStudyDir\\cgbk.txt"),"GBK");
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:\\JavaStudyDir\\dgbktoutf.txt" ) , "UTF-8");
int b;
while((b = isr.read( )) != -1) {
    osw.write(b);
}
osw.close();
isr.close();

需求 :利用字节流读取文件中的数据,每次读一整行,而且不能出现乱码

//1.字节流在读取中文的时候,是会出现乱码的,但是字符流可以搞定

//2.字节流里面是没有读一整行的方法的,只有字符缓冲流才能搞定

//生成文件

File file = new File("D:\\JavaStudyDir\\dgbktoutf.txt");

//生成字节流

FileInputStream fis = new FileInputStream(file);

//转换转换流

InputStreamReader fr = new InputStreamReader(fis);

//生成字符缓冲流

BufferedReader br = new BufferedReader(fr);

String str = null;

while((str = br.readLine())!=null){

System.out.println(str);

}

br.close();

总结:

16.序列流

代码:

代码:

细节:

17.练习

//需求:
//将多个自定义对象序列化到文件中,但是由于对象的个数不确定,反序列化流该如何读取呢?使用集合  
方法如下
ObjectStudent student1 = new ObjectStudent("张三",23);
ObjectStudent student2 = new ObjectStudent("李四",23);
ObjectStudent student3 = new ObjectStudent("王五",23);
ArrayList<ObjectStudent> arr = new ArrayList<>();
arr.add(student1);
arr.add(student2);
arr.add(student3);
File file = new File("D:\\JavaStudyDir\\a.txt");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arr);
oos.close();

//以下是反序列流代码

File file2 = new File("D:\\JavaStudyDir\\a.txt");
FileInputStream fis = new FileInputStream(file2);
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<ObjectStudent> arrReturn =(ArrayList<ObjectStudent>)ois.readObject();
for (ObjectStudent student : arrReturn) {
    System.out.println(student);
}
ois.close();

18.字节打印流

PrintStrea:字节打印流

PrintWriter:字符打印流

方法

代码如下:

19.字符打印流:需要手动开启,否则不会换行打印。

方法:

输出语句的缘由

总结:

20.压缩流和解压缩流:java只能识别zip

代码实现:

//压缩文件代码

//压缩文件
File srcFile = new File("D:\\JavaStudyDir.zip");
//解压后目的地址
File aimFile = new File("D:\\");
//调用方法
madeLarge(srcFile,aimFile);

  //解压文件方法代码

   public static void  madeLarge(File srcFile,File aimFile) throws IOException {
        //得到源文件输入流
        FileInputStream fis = new FileInputStream(srcFile);
        //将输入流转为压缩流
        ZipInputStream zis = new ZipInputStream(fis);
        //其实压缩流得到的是一个个 entry 对象
        ZipEntry entry;
        //循环遍历对象
        while ((entry = zis.getNextEntry()) != null) {
            //如果是文件夹则进行创建文件夹
            if (entry.isDirectory()) {
                //entry.getName()  得到的是这个文件的相对于srcFile()的绝对路径。故可以直接将目标文件夹进行拼接
                File file = new File(aimFile, entry.getName());
                file.mkdirs();
            } else {
                //生成目标文件
                File fileTwo = new File(aimFile, entry.getName());
                //转为输出流
                FileOutputStream fos = new FileOutputStream(fileTwo,true);
                int  len;
                byte[] bytes = new byte[1024*1024*5];
                //读取文件,方便等下输出
                while ( (len = zis.read(bytes))!= -1 ) {
                    //这个是读数组的方式加快速度
                    fos.write(bytes,0,len);
                    //用完关闭。
                }
                fos.close();
                //用完关闭单个zis文件通道
                zis.closeEntry();
            }

        }
        //整体关闭
        zis.close();
    }
}

代码:

  //压缩文件

    //文件来源
    File srcFile = new File("D:\\JavaStudyDirTwo");
    //文件压缩地址
    String parentStr = srcFile.getParent();
    System.out.println(parentStr);
    System.out.println(srcFile.getName());
    //压缩包名称
    File aimFile = new File(parentStr+"\\"+srcFile.getName()+".zip");//根据路径生成文件
    //生成输出流
    FileOutputStream fos = new FileOutputStream(aimFile);
    //生成关联压缩包
    ZipOutputStream zos = new ZipOutputStream(fos);

    madeMin(srcFile, srcFile.getName(), zos);


}

public  static void madeMin(File srcFile,String name,ZipOutputStream zos) throws IOException {
    File[] files = srcFile.listFiles();

    //生成读文件数组
    byte[] bytesT = new byte[1024*80];
    int len;

    for (File fileT : files) {
        if (fileT.isFile()) { //这里的fileT是绝对路径名的文件。
            //压缩包里每一个都是entry 对象。
            ZipEntry entry = new ZipEntry(name + "\\"+ fileT.getName());
            zos.putNextEntry(entry);
            FileInputStream fis = new FileInputStream(fileT);
           while ((len = fis.read(bytesT))!= -1){
              zos.write(bytesT,0,len);
          }
           zos.closeEntry();
           fis.close();
        }else {
            //递归的话会自动生成文件夹
         madeMin(fileT,name+"\\"+fileT.getName(),zos);


        }
    }

21.工具类

Commons:这个带了s

这个不带s

//这是FileUtils类
 /*
File srcFile = new File("D:\\JavaStudyDir\\b.txt");
File aimFile = new File("D:\\JavaStudyDir\\c.txt");
//复制文件
FileUtils.copyFile(srcFile,aimFile);
File srcfiles = new File("D:\\JavaStudyDir");
File aimfiles = new File("D:\\JavaStudyDirTest");
//这个方法是直接将文件夹里面的内容复制过去
FileUtils.copyDirectory(srcfiles,aimfiles);
File aimfilestwo = new File("D:\\JavaStudyDirTestTwo");
//这个方法是先创建文件夹,再把初始文件加进去。
FileUtils.copyDirectoryToDirectory(srcfiles,aimfilestwo);
//删除,清空,写入写出等操作就不一一展示了*/

//这是IOUtils类

/* File iosrcFile = new File("D:\\JavaStudyDir\\b.txt");
FileInputStream fis = new FileInputStream(iosrcFile);
File ioaimFile = new File("D:\\JavaStudyDir\\d.txt");
FileOutputStream fos = new FileOutputStream(ioaimFile);
IOUtils.copy(fis,fos);*/

//Hutools
//Hutools方法去文档里面找,好使。
FileUtil.appendString("这是一段测试的文件","D:\\JavaStudyDir\\b.txt", StandardCharsets.UTF_8);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值