IO流学习

IO流:存储和读取数据的解决方案

 

 

import java.io.FileOutputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
       //1.创建对象
        //写出 输入流 OutputStream
        //本地文件file
        FileOutputStream fos =new FileOutputStream("basic-code\\1.txt");
        //写出数据
        fos.write(97);
        //释放资源
        fos.close();
    }
}

 

 

import java.io.FileOutputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("basic-code\\1.txt");
        //fos.write(97);
        //fos.write(98);

        byte[] bytes={97,98,99,100,101};
       //fos.write(bytes);

        fos.write(bytes,1,3);

        fos.close();
    }
}

 

import java.io.FileOutputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("basic-code\\1.txt");

        String str ="yjybainchangsigema";
        byte[] bytes = str.getBytes();
       // System.out.println(Arrays.toString(bytes));
        fos.write(bytes);

        String str2 = "\r\n";
        byte[] bytes1 = str2.getBytes();
        fos.write(bytes1);

        String str3 = "come on";
        byte[] bytes2 = str3.getBytes();
        fos.write(bytes2);
        fos.close();
    }
}

 

import java.io.FileInputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        FileInputStream fio =new FileInputStream("basic-code\\1.txt");
        int read = fio.read();
        System.out.println(read);
        fio.close();
    }
}

import java.io.FileInputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        //字节输入流循环读取
        FileInputStream fis =new FileInputStream("baisc-code\\1.txt");
        int b;
        /*
        * read:表示读取数据,而且是读取一个数据就移动一次指针
        * 如果没有变量b
        * 假设文件数据abcde
        * while((fis.read())!=-1){
            System.out.println(fis.read);
            * 相当于a!=-1      输出b
            *       c!=-1      输出d
            *       e!=-1      输出-1
            * 因此第三方变量必须写
        * */
        while((b=fis.read())!=-1){
            System.out.println((char)b);

        }
        fis.close();
    }
}

文件拷贝的基本代码(小文件)

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
      //文件拷贝
        //1.创建对象
        FileInputStream fis =new FileInputStream("D:\\iii\\movie.mp4");
        FileOutputStream fos = new FileOutputStream("basic-code\\copy.mp4");
        //2.拷贝
        //核心思想:边读边想
        int b;
        while((b =fis.read())!=-1){
            fos.write(b);
        }
        //3.释放资源
        //规则:先开的最后关闭
        fos.close();
        fis.close();
        
    }
}

 

 

import java.io.FileInputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        //1.创建对象
        FileInputStream fis = new FileInputStream("basic-code\\1.txt");
        //2.读取数据
        byte[] bytes = new byte[2];
        //一次读取多个字节数据 具体多少 跟数组的长度有关
        //返回值 本子读取到多少个字节数据
        int len1 = fis.read(bytes);
        System.out.println(len1);//2

        String str1 = new String(bytes);
        System.out.println(str1);


        int len2 = fis.read(bytes);
        System.out.println(len2);//2

        String str2 = new String(bytes);
        System.out.println(str2);

        int len3 = fis.read(bytes);
        System.out.println(len3);//2

        String str3 = new String(bytes);
        System.out.println(str3);

        fis.close();

    }
}

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        //文件拷贝改写
        long start = System.currentTimeMillis();
        FileInputStream fis = new FileInputStream("D:\\aaa");
        FileOutputStream fos = new FileOutputStream("baisc-code\\a");
        int len;
        byte[] bytes =new byte[1025*1024*5];
        while((len=fis.read())!=-1){
            fos.write(bytes,0,len);
        }
        fos.close();
        fis.close();

        long end = System.currentTimeMillis();

        System.out.println(end-start);
    }
}

 

 字符集详解(ASCII, GBK)

 

 

 

 

 

 

 

 

import java.io.FileInputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        //字节流读取中文会出现乱码
        FileInputStream fis = new FileInputStream("basic-code\\a");
        int b;
        while((b= fis.read())!=-1){
            System.out.println((char)b);
        }
        fis.close();
    }
}

数据流一个个拷贝 肯定就会出现乱码

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        //1.创建对象
        FileInputStream fis = new FileInputStream("basic-code\\a.txt");
        FileOutputStream fos =new FileOutputStream("basic-code\\1.txt");
        //2.拷贝
        int b;
        while((b=fis.read())!=-1){
            fos.write(b);
        }
        //3.释放资源
        fos.close();
        fis.close();
    }
}

记事本!数据不会丢失目的地和数据源保持一致

 

 

import java.io.IOException;
import java.util.Arrays;

public class Test {
    public static void main(String[] args) throws IOException {
        //1.编码
        String str ="ai你哟";
        byte[] bytes1 = str.getBytes();
        System.out.println(Arrays.toString(bytes1));//???

        byte[] bytes2 = str.getBytes("GBK");
        System.out.println(Arrays.toString(bytes2));//???

        //2.解码
        String str2 = new String(bytes1);
        System.out.println(str2);

        String str3 = new String(bytes1,"GBK");
        System.out.println(str3);
    }
}

 

 

 

 

import java.io.FileReader;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        //1.创建对象并关联本地文件
        FileReader fr = new FileReader("basic-code\\1.txt");
        //2.读取数据 read()
        //字符流的底层也是字节流,默认也是一个字节一个字节的读取的.
        //如果遇到中文就会一次读取多个 GBK依次读两个字节,UTF-8一次读三个字节
        //在读取之后 方法的底层还会进行解码并转成十进制
        //最终把这个十进制作为返回值
        //这个十进制的数据也表示在字符集上的数字
        // 英文:文件里面二进制数据 0110 0001
        //read方法进行获取a,解码并转成十进制97
        //中文:文件里面的二进制数据 11100110  10110001  10001001
        //read方法进行读取,解码并转成十进制27721
        
        //我想看到中文汉字 就是把这些十进制数据 进行强转
        int ch;
        while((ch=fr.read())!=-1){
            System.out.print((char)ch);
        }
        //释放资源
        fr.close();
        
    }
}
import java.io.FileReader;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        //1.创建对象
        FileReader fr =new FileReader("basic-code\\1.txt");
        //2.读取数据
        char[] chars =new char[2];
        int len;
        //fr.read();//读取数据,解码,强转三步合并了,把强转之后的字符放到数组当中
        //空参的read()+强制类型转换
        
        while((len = fr.read(chars))!=-1){
            //把数组中的数据变成字符串再进行打印
            System.out.println(new String(chars,0,len));
        }
        //3.释放资源
        fr.close();

    }
}
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
       //字节输出流:
        FileOutputStream fos = new FileOutputStream("basic-code\\1.txt");
        fos.write(97);//字节流 每次只能操作一个字节 255
        fos.close();
        //字符输出流:
        FileWriter fw =new FileWriter("basic-code\\a.txt");
        fw.write(7777);//根据字符集的编码方式进行编码 把编码之后的数据写到文件中去
        fw.close();
        
        FileWriter fw1= new FileWriter("basic-code\\1.txt",true);//续写开关
        //fw1.write("你好");
        char[] chars ={'a','b','c','我'};
        fw.write(chars);
        fw1.close();
        
    }
}

 

 

 

 

 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        //拷贝文件夹 考虑子文件
        //1.创建对象表示数据源
        File src =new File("D:\\aaa\\src");
        //2.创建对象表示目的地
        File dest = new File("D:\\aaa\\dest");

        //调用方法开始拷贝
        copydir(src,dest);

    }

    /*
    * 作用:拷贝文件夹
    * 参数一:数据源
    * 参数二:目的地
    *
    * */
    private static void copydir(File src, File dest) throws IOException {
        dest.mkdirs();
        递归
        //进入数据源
        File[] files = src.listFiles();
        //遍历数组
        for (File file : files) {
            if(file.isFile()){
                //判断文件 拷贝 
                FileInputStream fis =new FileInputStream(file);
                FileOutputStream fos =new FileOutputStream(new File(dest,file.getName()));
                byte[] bytes = new byte[1024];
                int len;
                while((len=fis.read(bytes))!=-1){
                    fos.write(bytes,0,len);
                }
                fos.close();
                fis.close();
            }else{
                //判断文件夹 递归
                copydir(file,new File(dest,file.getName()));
            }
        }



    }
}

        //文件加密
        //原始文件
        FileInputStream fis =new FileInputStream("C:\\girl.jpg");
        //加密处理
        FileOutputStream fos =new FileOutputStream("C:\\ency.jpg");
        //加密处理
        int b;
        while((b=fis.read())!=-1){
            fos.write(b ^2);//随便异或一个数字
        }
        fos.close();
        fis.close();
        //这个程序操作完成后就可以将源文件删除了 这样别人也不知道是什么东西等到你想看了
        //你再进行解密
      //前置知识
        /*
         *  ^:异或
         * 两边相同:false
         * 两边不同:true
         *  0:false
         *  1:true
         *
         * 100:110100
         * 10:1010
         *
         *      1100100
         *     ^0001010
         * ________________
         *      1101110    --->110
         *   ^  0001010
         * ________________
         *      1100100    --->100
         * System.out.println(100^10);//110
         * System.out.println(100^10^10);//100
         *
         * */
        //文件加密
        //原始文件
        FileInputStream fis =new FileInputStream("C:\\ency.jpg");
        //加密处理
        FileOutputStream fos =new FileOutputStream("C:\\redu.jpg");
        //加密处理
        int b;
        while((b=fis.read())!=-1){
            fos.write(b ^2);//随便异或一个数字
        }
        fos.close();
        fis.close();
        //这个程序操作完成后就可以将源文件删除了 这样别人也不知道是什么东西等到你想看了
        //你再进行解密

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

public class Test {
    public static void main(String[] args) throws IOException {
        //修改文件中的数据
        //1.读取数据
        FileReader fr =new FileReader("basic-code\\a.txt");
        StringBuilder sb =new StringBuilder();
        int ch;
        while((ch = fr.read())!=-1){
            sb.append((char)ch);
        }
        fr.close();
        System.out.println(sb);
        //2.排序
        String str =sb.toString();
        String[] arrstr =str.split("-");

        ArrayList<Integer>list = new ArrayList<>();
        for (String s : arrstr) {
            int i = Integer.parseInt(s);
            list.add(i);
        }
        //System.out.println(list);
        Collections.sort(list);
        
        //3.写出
        FileWriter fw =new FileWriter("basic-code\\a.txt");
        for (int i = 0; i < list.size(); i++) {
            if(i==list.size()-1){
                fw.write(list.get(i)+"");//如果直接写数字 文件会变成ASCII码
                
            }else{
                fw.write(list.get(i)+"-");
            }
        }
        fw.close();
        
    }
}

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
//细节:文件中的数据不要换行  如果加了换行会有\r\n 读取也会读到
//bom头---占三个字节   编码改为ANSI
public class Test {
    public static void main(String[] args) throws IOException {
        //修改文件中的数据
        //1.读取数据
        FileReader fr =new FileReader("basic-code\\a.txt");
        StringBuilder sb =new StringBuilder();
        int ch;
        while((ch = fr.read())!=-1){
            sb.append((char)ch);
        }
        fr.close();
        System.out.println(sb);
        //2.排序
        Integer[] arr = Arrays.stream(sb.toString().split("-"))
                .map(Integer::parseInt)
                .sorted()
                .toArray(Integer[]::new);
        //System.out.println(arr);


        //3.写出
        FileWriter fw = new FileWriter("C:\\yjy");
        String s = Arrays.toString(arr).replace(", ","-");
        String result = s.substring(1,s.length()-1);
        //System.out.println(result);
        fw.write(result);
        fw.close();
    }
}

 

 

public class Test {
    public static void main(String[] args) throws IOException {
        //1.创建缓冲流的对象
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("basic-code\\a.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("basic-code\\1.txt"));

        //2.循环读取
        int b;
        while ((b = bis.read()) != -1) {
            bos.write(b);
        }
        //3.释放资源
        bos.close();
        bis.close();
    }
}
public class Test {
    public static void main(String[] args) throws IOException {
      //一次读写一个字节数组
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("basic-code\\a.txt"));
        BufferedOutputStream bos =new BufferedOutputStream(new FileOutputStream("basic-code\\b.txt"));
        
        byte[] bytes =new byte[1024];
        int len;
        while((len=bis.read(bytes))!=-1){
            bos.write(bytes,0,len);
        }
        bos.close();
        bis.close();
    }
}

 

 

 

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class Test {
    public static void main(String[] args) throws IOException {
        //两个缓冲区之间这不也是一个字节一个字节的进行倒手的吗?? 速度为什么快了?
        //因为这一段是在内存中运行的速度非常的快

        /*字符缓冲输入流:
        * 构造方法:public BufferedReader(Reader r)
        * 特有方法:public String readLine() 读一整行*/
        
        //readLine 方法在读取的时候 一次读一整行 遇到空格换行结束
        //但是他不会把回车读到内存当中 
        //1.创建字符缓冲输入流的对象
        BufferedReader br =new BufferedReader(new FileReader("basic-code\\1.txt"));
        //2.读取数据
//        String line = br.readLine();
//        System.out.println(line);
        
        String line;
        while((line=br.readLine())!=null){
            System.out.println(line);
        }
        
        //释放资源
        br.close();
    }
}
public class Test {
    public static void main(String[] args) throws IOException {
        /*字符缓冲输出流
        * 构造方法:public BufferedWriter(writer r)
        * 特有方法:public void newLine() 跨平台换行*/

        //1.创建字符缓冲输出流的对象
        BufferedWriter bw =new BufferedWriter(new FileWriter("b.txt"));
        //2.写出数据
        bw.write("你嘴角上扬的样子,百度搜索不到");
        bw.newLine();
        bw.write("以后我结婚你一定要来 ,没有新娘我会很尴尬");
        //3.释放资源
        bw.close();
    }
}

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException {
        //拷贝文件 
        //四种方法拷贝文件,并统计各自用时
        //字节流的基本流:依次读写一个字节
        //字节流的基本流:一次读写一个字节数组
        //字节缓冲流:一次读写一个字节
        //字节缓冲流:一次读写一个字节数组

        long start = System.currentTimeMillis();
        method1();
        method2();//16
        method3();//95
        method4();//17
        long end=System.currentTimeMillis();
        System.out.println((end-start)/1000.0+"秒");
        
    }

    private static void method3() throws IOException {
        //字节缓冲流
        BufferedInputStream bis =new BufferedInputStream(new FileInputStream("1.txt"));
        BufferedOutputStream bos =new BufferedOutputStream(new FileOutputStream("2.txt"));

        int b;
        while((b=bis.read())!=-1){
            bos.write(b);
        }
        bos.close();
        bis.close();
    }

    private static void method4() throws IOException {


        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("1.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("2.txt"));

        byte[] bytes = new byte[8192];
        int len;
        while ((len = bis.read(bytes)) != -1) {
            bos.write(bytes,0,len);
        }
        bos.close();
        bis.close();
    }

    private static void method2() throws IOException {

        FileInputStream fis = new FileInputStream("C:\\1.txt");
        FileOutputStream fos=new FileOutputStream("1.txt");
        byte[] bytes= new byte[1024];
        int len;
        while((len=fis.read(bytes))!=-1){
            fos.write(bytes,0,len);
        }
        fos.close();
        fis.close();



    }

    private static void method1() throws IOException {
        FileInputStream fis = new FileInputStream("C:\\1.txt");
        FileOutputStream fos = new FileOutputStream("1.txt");
        int b;
        while ((b = fis.read()) != -1) {
            fos.write(b);
        }
        fos.close();
        fis.close();

    }


}

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Test {
    public static void main(String[] args) throws IOException {
        //需求:把<出师表>的文章顺序进行恢复到一个新文件中
        
        //1.读取数据
        BufferedReader br =new BufferedReader(new FileReader("basic-code"));
        String line;
        ArrayList<String>list=new ArrayList<>();
        while((line=br.readLine())!=null){
          //  System.out.println(line);
            list.add(line);
        }
        br.close();
        //2.排序
        //排序规则:按照每一行前面的序号进行排序
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                //获取o1,o2的序号
                int i = Integer.parseInt(o1.split("\\.")[0]);
                int i1 = Integer.parseInt(o2.split("\\.")[0]);
                return i-i1;
            }
        });
        //写出
        BufferedWriter bw =new BufferedWriter(new FileWriter("1.txt"));
        for (String s : list) {
            bw.write(s);
            bw.newLine();
        }
        bw.close();
        
    }
}
import java.io.*;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class Test {
    public static void main(String[] args) throws IOException {
        //需求:把<出师表>的文章顺序进行恢复到一个新文件中
        BufferedReader br =new BufferedReader(new FileReader("1.txt"));
        String line;
        TreeMap<Integer,String> tm = new TreeMap<>();
        while((line=br.readLine())!=null){
            String[] arr =line.split("\\.");
            //0:序号  1:内容
            tm.put(Integer.parseInt(arr[0]),line);
            
        }
        br.close();
        //System.out.println(tm);
        //2.写出数据
        BufferedWriter bw =new BufferedWriter(new FileWriter("basic-code"));
        Set<Map.Entry<Integer,String>>entries = tm.entrySet();
        for(Map.Entry<Integer,String>entry:entries){
            String value = entry.getValue();
            bw.write(value);
            bw.newLine();
        }
        bw.close();
    }
}

 

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException {
       //能用计数器的知识来做吗?不能 因为变量创建在内存中 程序重启 又能够再来三次
        //为了永久化存储所以要保存在文件当中
        //1.把文件中的数字读取到内存中
        //一次读一行 而不是读一个
        BufferedReader br =new BufferedReader(new FileReader("basic-code"));
        String line =br.readLine();
        int count = Integer.parseInt(line);
        //表示当前软件又运行了一次
        count++;

        //2.判断
        if(count<=3){
            System.out.println("欢迎使用本软件,第"+count+"次免费使用");
        }else{
            System.out.println("本软件只能使用三次,请注册会员继续使用");
        }
        //<=3:正常运行
        //>3:不能运行
        //3.把自增之后的count写出到文件当中
        BufferedWriter bw = new BufferedWriter(new FileWriter("basic-code"));
        //缓冲区输出流在关联文件的时候,文件存在就会清空
        //原则:IO:随用随创建
        //什么时候不用就关掉
        bw.write(count+"");//97 a
        bw.close();

    }
}

 

import java.io.*;
import java.nio.charset.Charset;

public class Test {
    public static void main(String[] args) throws IOException {
        //利用转换流按照指定字符编码读取(了解)
        
        /*
        * 因为JDK11:这种方法被淘汰了  --->替代方案(掌握)*/
        
//        //1.创建对象并指定字符编码(了解即可)
//        InputStreamReader isr =new InputStreamReader(new FileInputStream("basic-code"),"GBK");
//        //2.读取数据
//        int ch;
//        while((ch=isr.read())!=-1){
//            System.out.println((char)ch);
//        }
//        //3.释放资源
//        isr.close();

        //掌握
        FileReader fr = new FileReader("basic-code", Charset.forName("GBK"));
       // 2.读取数据
        int ch;
        while((ch=fr.read())!=-1){
            System.out.println((char)ch);
        }
        //3.释放资源
        fr.close();
    }
}

import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;

public class Test {
    public static void main(String[] args) throws IOException {
        //利用转换流按照指定字符编码写出(了解)

//        //1.创建转换流对象
//        OutputStreamWriter osw =new OutputStreamWriter(new FileOutputStream("basic-code"),"GBK");
//        //2.写出数据
//        osw.write("你好你好");
//        //3.释放资源
//        osw.close();
        
        //替代方案
        FileWriter fw = new FileWriter("basic-code", Charset.forName("GBK"));
        fw.write("你好你好");
        fw.close();
    
    }
}

 

import java.io.*;
import java.nio.charset.Charset;

public class Test {
    public static void main(String[] args) throws IOException {
        //将本地文件中GBK文件 转成UTF-8
        
        //1.JDK以前的方案
        InputStreamReader isr = new InputStreamReader(new FileInputStream("basic-code"),"GBK");
        OutputStreamWriter osw =new OutputStreamWriter(new FileOutputStream("basic-code1"),"UTF-8");
        
        int b;
        while ((b= isr.read())!=-1){
            osw.write(b);
        }
        osw.close();
        isr.close();
        
        
        
        //替代方案
        FileReader fr =new FileReader("basic-code", Charset.forName("GBK"));
        FileWriter fw =new FileWriter("basic-code1",Charset.forName("UTF-8"));
        int b;
        while((b=fr.read())!=-1){
            fw.write(b);
        }
        fw.close();
        fr.close();
    }
}

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException {
        //利用字节流读取文件中的数据 每次读一整行,而且不能出现乱码
        //1.字节流在读取中文的时候,是会出现乱码的,但是字符流可以搞定
        //2.字节流里面没有读一整行的方法的 只有字符缓冲流可以搞定

//        FileInputStream fis= new FileInputStream("basic-code");
//        InputStreamReader isr =new InputStreamReader(fis);
//
//        BufferedReader br =new BufferedReader(isr);
//        String s = br.readLine();
//        br.close();

        BufferedReader br =new BufferedReader(new InputStreamReader(new FileInputStream("yjy.txt")));
        String line;
        while((line=br.readLine())!=null){
            System.out.println(line);
        }
        br.close();


    }
}

 

 

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Test {
    public static void main(String[] args) throws IOException {
        /*
        * serializable接口里面没有抽象方法,标记型接口
        * 一旦实现了这个接口 那么就表示当前的student类可以被序列化
        * 理解:
        * 一个物品的合格证
        * */
       //序列化流
        Student stu =new Student("zhangsan",23);
        ObjectOutputStream oos =new ObjectOutputStream(new FileOutputStream("basic-code\\a.txt"));
        oos.writeObject(stu);
        oos.close();

    }
}
import java.io.Serializable;

public class Student implements Serializable {
    private String name;
    private int age;


    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "Student{name = " + name + ", age = " + age + "}";
    }
}

 

 

自己设置一个提示-版本号

在搜索框搜索Serializable

public class Student implements Serializable {
    @Serial
    private static final long serialVersionUID = 5498121245996411513L;
    // private static final long serialVersionUID = 1L;

    private String name;
    private int age;
    private String address;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "Student{name = " + name + ", age = " + age + "}";
    }
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ///用对象流读写多个对象
        //需求:
        //将多个自定义对象序列化到文件中,但是由于对象的个数不确定,反序列化流该如何读取呢?
        
        Student s1 =new Student("zhangsan",23,"南京");
        Student s2 =new Student("lisi",24,"重庆");
        Student s3 =new Student("wangwu",25,"北京");
        //序列化多个对象
        ArrayList<Student>list =new ArrayList<>();
        list.add(s1);
        list.add(s2);
        list.add(s3);
        

        ObjectOutputStream oos =new ObjectOutputStream(new FileOutputStream("basic-code"));
        oos.writeObject(list);
     
        
        oos.close();
        
    }
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

public class Demo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //反序列化流的对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("basic-code"));
//
//        Student s1 = (Student) ois.readObject();
//        Student s2 = (Student) ois.readObject();
//        Student s3 = (Student) ois.readObject();
        ArrayList<Student>list = (ArrayList<Student>) ois.readObject();
        for (Student student : list) {
            System.out.println(student);
        }


        ois.close();

    }
}

 

 

 

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;

public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //打印流
        
        //1.创建字节打印流的对象
        PrintStream ps =new PrintStream(new FileOutputStream("myio\\1.txt"),true, Charset.forName("UTF-8"));
        //2.写出数据
        ps.println(97);//写出+自动刷新+自动换行
        ps.print(true);
        ps.println();
        ps.printf("%s 爱上了 %s","阿珍","阿强");
        //3.释放资源
        ps.close();
        
    }
}
public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //打印流

     //1.创建字符打印流
        PrintWriter pw =new PrintWriter(new FileWriter("basic-code"),true);
        pw.println("dhuaidhwahdo");
        pw.print("你好你好");
        pw.close();
    }
}

解压缩流/压缩流

 

 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //1.创建一个File表示要解压的压缩包
        File src =new File("D:\\aaa.zip");
        //2.创建File对象表示解压的目的地
        File dest = new File("D:\\");
        
        //调用方法
        unzip(src,dest);
        
    }
    //定义一个方法用来解压
    public static void unzip(File src,File dest) throws IOException {
        //解压的本质:把压缩包里面的每一个文件或者文件夹读取出来 按照层级拷贝到目的地当中
        
        //创建一个解压缩流用来读取压缩包中的数据
        ZipInputStream zip =new ZipInputStream(new FileInputStream(src));
        //先获取到压缩包里面的每一个zipentry对象
        
//        for (int i = 0; i < 100; i++) {
//            ZipEntry entry = zip.getNextEntry();
//            System.out.println(entry);//找不到就是返回null
//        }
        
        //表示当前在压缩包中获取到的文件或者文件夹
        ZipEntry entry;
        while ((entry = zip.getNextEntry())!=null){
            System.out.println(entry);
            
            //文件夹:需要在目的地dest处创建一个同样的文件夹
            //文件:需要读取到压缩包中的文件,并把他存放到目的地dest文件夹中(按照层级目录进行存放)
            if(entry.isDirectory()){
                //文件夹:需要在目的地dest处创建一个同样的文件夹
                File file =new File(dest,entry.toString());
                file.mkdirs();
            }else{
                //文件:需要读取到压缩包的文件,并把他存放到目的地dest文件夹中(按照层级目录进行存放)
                FileOutputStream fos = new FileOutputStream(new File(dest,entry.toString()));
                int b;
                while((b =zip.read())!=-1){
                    //写到目的地
                    fos.write(b);
                }
                fos.close();
                //表示在压缩包中的一个文件处理完毕了
                zip.closeEntry();
            }
            
            
        }
        zip.close();
        
      
    }
}

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
       //压缩单个文件 ->压缩包

        //1.创建File对象表示要压缩的文件
        File src = new File("D:\\yjy.txt");
        //2.创建File对象表示压缩包的位置
        File dest = new File("D:\\");
        //3.调用方法来压缩
        toZip(src,dest);

    }
    /*
    * 作用:压缩
    * 参数一:表示要压缩的文件
    *
    * 参数二:表示压缩包的位置
    *
    * */
    public static void toZip(File src,File dest) throws IOException {
        //1.创建压缩流关联压缩包
        ZipOutputStream zos =new ZipOutputStream(new FileOutputStream(new File(dest,"yjy.zip")));
        //2.创建ZipEntry对象,表示压缩包里面的每一个文件和文件夹
        ZipEntry entry = new ZipEntry("yjy.txt");
        //3.把ZipEntry对象放到压缩包当中
        zos.putNextEntry(entry);
        //4.把src里面的数据写到压缩包中
        FileInputStream fis = new FileInputStream(src);
        int b;
        while((b=fis.read())!=-1){
            zos.write(b);
        }

        zos.closeEntry();
        zos.close();
    }
}

 

import java.io.File;
import java.io.IOException;

public class DEMO {
    public static void main(String[] args) throws IOException {
//        File src =new File("basic-code\\1.txt");
//        File dest =new File("basic-code\\copy.txt");
//
//        FileUtils.copyFile(src,dest);//用这个包直接拷贝了


//        File src =new File("D:\\aaa");
//        File dest =new File("D:\\bbb");
//        FileUtils.copyDirectory(src,dest);

//        File src =new File("D:\\aaa");
//        File dest =new File("D:\\bbb");
//        FileUtils.copyDirectoryToDirectory(src,dest);
        //作用:bbb:里面有aaa然后有aaa里面的东西

        File src =new File("D:\\aaa");
        FileUtils.deleteDirectory(src);

        File dest =new File("D:\\bbb");
        FileUtils.cleanDirectory(dest);



    }
}

 

 

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DEMO {
    public static void main(String[] args) throws IOException {
        //Hutool
        //因为里面的方法都是静态的所以直接用类名就可以调用了
        File file = FileUtil.file("D:\\aaa", "bbb", "a.txt");
        System.out.println(file);//D:\aaa\bbb\a.txt
        
        File f =new File("a.txt");
        f.createNewFile();//如果父级路径不存在那么会报错
        
        //Hutool 里面的touch方法如果找不到这个父级路径会帮我们创建
        File touch = FileUtil.touch(file);

        System.out.println(touch);


        ArrayList<String>list =new ArrayList<>();
        list.add("aaa");
        list.add("aaa");
        list.add("aaa");

        File file1 = FileUtil.writeLines(list, "D:\\a.txt", "UTF-8", false);
        System.out.println(file1);

        File file2 = FileUtil.appendLines(list, "D:\\a.txt", "UTF-8");
        System.out.println(file2);

        List<String> strings = FileUtil.readLines("D:\\a.txt", "UTF-8");
        System.out.println(list);
    }
}

官网:
    https://hutool.cn/
API文档:
    https://apidoc.gitee.com/dromara/hutool/

中文使用文档:
    https://hutool.cn/docs/#/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/250192.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

TrustGeo代码理解(七)preprocess.py

代码链接:https://github.com/ICDM-UESTC/TrustGeo 一、导入各种模块和数据库 # Load data and IP clusteringimport math import random import pandas as pd import numpy as np import argparse from sklearn import preprocessing from lib.utils import MaxMinScaler …

列表优先于数组

在Java中&#xff0c;列表&#xff08;List&#xff09;通常优于数组&#xff0c;因为列表提供了更灵活的操作和动态调整大小的能力。下面是一个例子&#xff0c;展示了为什么在某些情况下使用列表比数组更好&#xff1a; import java.util.ArrayList; import java.util.List;…

AtCoder ABC周赛2023 12/10 (Sun) D题题解

目录 原题截图&#xff1a; 题目大意&#xff1a; 主要思路&#xff1a; 注&#xff1a; 代码&#xff1a; 原题截图&#xff1a; 题目大意&#xff1a; 给定两个 的矩阵 和 。 你每次可以交换矩阵 的相邻两行中的所有元素或是交换两列中的所有元素。 请问要使 变换至…

python封装执行cmd命令的方法

一、前置说明 在自动化时&#xff0c;经常需要使用命令行工具与系统进行交互&#xff0c;因此可以使用python封装一个执行cmd命令的方法。 二、代码实现 import subprocess import timefrom common.exception import RunCMDError from common.logger import loggerclass Cmd…

使用Matlab实现声音信号处理

利用Matlab软件对声音信号进行读取、放音、存储 先去下载一个声音文件&#xff1b;使用这个代码即可 clear; clc; [y, Fs] audioread(xxx.wav); plot(y); y y(:, 1); spectrogram(y); sound(y, Fs); % player audioplayer(y, Fs);y1 diff(y(:, 1)); subplot(2, 1, 1); pl…

【Spark精讲】Spark五种JOIN策略

目录 三种通用JOIN策略原理 Hash Join 散列连接 原理详解 Sort Merge Join 排序合并连接 Nested Loop 嵌套循环连接 影响JOIN操作的因素 数据集的大小 JOIN的条件 JOIN的类型 Spark中JOIN执行的5种策略 Shuffle Hash Join Broadcast Hash Join Sort Merge Join C…

关于MySQL的bigint问题

MySQL的bigint(8)能存多大数值&#xff1f; MySQL的BIGINT(8)可以存储的数值范围是从-9,223,372,036,854,775,808到9,223,372,036,854,775,807。这是因为BIGINT数据类型在MySQL中使用8字节进行存储&#xff0c;每个字节有8位&#xff0c;所以总共可以表示2^64个不同的整数。 …

亚太地区是Aleo下一个重点市场!ZK技术将重塑区块链世界!

4 年&#xff0c;3 亿美元&#xff0c;基于 ZK 的隐私公链&#xff0c;是 Aleo 最直观的三个标签。区块链的致富效应&#xff0c;已经让传统金融蠢蠢欲动&#xff0c;想参与Aleo私募和头矿的朋友请于文末添加微信。 对于Aleo副总裁兼业务发展主管Joanna Zeng来说&#xff0c;近…

[NAND Flash 4.1] Flash(闪存)存储器底层原理 | 闪存存储器重要参数

依公知及经验整理&#xff0c;原创保护&#xff0c;禁止转载。 专栏 《深入理解NAND Flash》 <<<< 返回总目录 <<<< ​全文 5000 字。 从底层物理原理上了解 Nand Flash。 1. 存储器诞生&#xff1a; 现代计算机使用存储器来存储数据&#xff0c;其…

【FPGA】Verilog:解码器 | 实现 2-4 解码器

实践内容&#xff1a;解释 2 至 4 解码器的结果和仿真过程 (包括真值表创建和 k 映射、AND 门&#xff09;。 0x00 解码器&#xff08;Decoder&#xff09; 解码器是一种根据输入信号从多个输出 bit 中只选择一个的设备。 例如&#xff0c;如果有一个解码器接收一个 2 位二进…

章鱼网络 Community Call #16|逐步过渡到回购和销毁模型

香港时间2023年12月8日12点&#xff0c;章鱼网络举行第16期 Community Call。 自2023年4月份提出 Octopus 2.0 计划以来&#xff0c;我们一直致力于将这一愿景变为现实。感谢核心团队和章鱼社区的共同努力&#xff0c;我们决定于 12月17日正式推出 Octopus 2.0。 Community Ca…

node.js mongoose Aggregate介绍

目录 简述 Aggregate的原型方法 aggregate进行操作 简述 在 Mongoose 中&#xff0c;Aggregate 是用于执行 MongoDB 聚合操作的类。MongoDB 聚合操作是一种强大的数据处理工具&#xff0c;可以用于对集合中的文档进行变换和计算 通过Model.aggregate创建一个aggregate(Agg…

python批量实现labelImg标注的 xml格式数据转换成 txt格式保存

# -*- coding: utf-8 -*- import os import xml.etree.ElementTree as ETdirpath ********** # 原来存放xml文件的目录 newdir ********* # 修改label后形成的txt目录if not os.path.exists(newdir):os.makedirs(newdir)dict_info {sf6: 0, thermometer: 1,…

jmeter 如何循环使用接口返回的多值?

有同学在用jmeter做接口测试的时候&#xff0c;经常会遇到这样一种情况&#xff1a; 就是一个接口请求返回了多个值&#xff0c;然后下一个接口想循环使用前一个接口的返回值。 这种要怎么做呢&#xff1f; 有一定基础的人&#xff0c;可能第一反应就是先提取前一个接口返回…

低代码与工业4.0:数字化转型的完美伴侣

引言 工业4.0代表了制造业的一场革命&#xff0c;它将数字化、智能化和自动化引入了制造流程&#xff0c;重新定义了生产方式和企业运营。在这个数字时代&#xff0c;低代码技术崭露头角&#xff0c;成为工业4.0的强力支持者。本文将探讨低代码技术与工业4.0之间的紧密联系&am…

Linux 进程通信

文章目录 匿名管道匿名管道使用匿名管道原理匿名管道读写 命名管道命名管道使用命名管道特性 共享内存共享内存原理共享内存使用 补充说明 补充说明部分为相关函数和不太重要的概念介绍 匿名管道 匿名管道使用 使用方法一&#xff1a; 使用函数介绍&#xff1a; #include &…

DevEco Studio自定义代码颜色

这里以ArkTS代码颜色举例 进入设置&#xff08;快捷键CtrlAltS&#xff09; 选择Editor > Color Scheme > JavaScript 由于之前用习惯VsCode了&#xff0c;这里以注释颜色举例&#xff0c;变为绿色。 上面说的不是以ArkTS代码颜色举例吗&#xff1f;为什么选择JavaScr…

极坐标下的牛拉法潮流计算14节点MATLAB程序

微❤关注“电气仔推送”获得资料&#xff08;专享优惠&#xff09; 潮流计算&#xff1a; 潮流计算是根据给定的电网结构、参数和发电机、负荷等元件的运行条件&#xff0c;确定电力系统各部分稳态运行状态参数的计算。通常给定的运行条件有系统中各电源和负荷点的功率、枢纽…

产品经理之如何编写需求PRD文档(医疗HIS项目详细案例模板)

目录 前言 一.需求文档的含义 二.需求文档的作用及目的 三.编写前的准备 四.需求大纲 五.案例模板 前言 继上两篇的可行性分析文档和竞品分析报告&#xff0c;本篇将继续介绍如何编写PRD文档&#xff0c;并且会附上以医疗项目为例的模板 一.需求文档的含义 需求文…

设计模式——享元模式(结构型)

引言 享元模式是一种结构型设计模式&#xff0c; 它摒弃了在每个对象中保存所有数据的方式&#xff0c; 通过共享多个对象所共有的相同状态&#xff0c; 让你能在有限的内存容量中载入更多对象。 问题 假如你希望在长时间工作后放松一下&#xff0c; 所以开发了一款简单的游戏…
最新文章