java io流专题

 来自哔哩哔哩韩顺平讲Java

JAVA中针对文件的读写操作设置了一系列的流,其中主要有FileInputStream,FileOutputStream,FileReader,FileWriter四种最为常用的流

File基本信息

package com.file;

import org.junit.Test;

import java.io.File;

/**
 * @author lyt
 * @description
 * @date 2021/10/12 10:16
 */
public class FileInformation {
    public static void main(String[] args) {

    }
    //获取文件的信息
    @Test
    public void info(){
        //先创建文件对象
        File file = new File("d:\\news1.txt");
        //调用相应的方法得到对应信息
        System.out.println("文件名称="+file.getName());

        System.out.println("文件绝对路径="+file.getAbsolutePath());

        System.out.println("文件父级目录="+file.getParent());

        //utf8字符集编码格式:一个英文字母对应一个字节数,一个汉字对应三个字节数
        System.out.println("文件大小(字节)="+file.length());

        System.out.println("文件是否存在="+file.exists());//T

        System.out.println("是不是一个文件="+file.isFile());//T

        System.out.println("是不是一个目录="+file.isDirectory());//F

    }
}

创建文件

package com.file;

import org.junit.Test;

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

/**
 * @author lyt
 * @description 创建文件
 * @date 2021/10/12 9:47
 */
public class FileCreate {
    public static void main(String[] args) {

    }

    //方式1:new File(String pathname)
    @Test
    public void create01() {
        String filePath = "d:\\news1.txt";
        File file = new File(filePath);
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //方式2: new File(File parent,String child)//根据父目录文件+子路径构建
    //d:\\news2.txt     parent是d:\\
    @Test
    public void create02(){
        File parentFile = new File("d:\\");
        String fileName="news2.txt";
        //这里的file对象,在Java程序中,只是一个对象
        File file = new File(parentFile, fileName);
        try {
            //只有执行了createNewFile方法,才会在磁盘创建该文件
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //方式3  new File(String parent,String child)//根据父目录+子路径构建
    @Test
    public void create03(){
        //两种
        String parentPath="d:\\";
        //String parentPath="d:/";
        String fileName="news3.txt";
        File file = new File(parentPath, fileName);
        try {
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

删除文件、创建目录 

package com.file;

import org.junit.Test;

import java.io.File;
import java.io.Reader;

/**
 * @author lyt
 * @description
 * @date 2021/10/12 10:31
 */
public class Directory {
    public static void main(String[] args) {

    }

    //判断 d:\\news1.txt 是否存在,如果存在就删除
    @Test
    public void m1(){
        String filePath="d:\\news1.txt";
        File file = new File(filePath);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println(filePath+"删除成功");
            }else{
                System.out.println(filePath+"删除失败");
            }
        }else{
            System.out.println(filePath+"该文件不存在");
        }
    }

    //判断 d:\\demo02是否存在,存在就删除,否则提示不存在
    //这里需要体会到,在Java编程中,目录也被当作文件
    @Test
    public void m2(){
      String filePath="d:\\demo02";
        File file =new File(filePath);
        if(file.exists()){
            if(file.delete()){
                System.out.println("删除成功");
            }else{
                System.out.println("删除失败");
            }
        }else{
            System.out.println("目录不存在");
        }
    }

    //判断 d:\\demo\\a\\b\\c 目录是否存在,如果存在就提示已经存在,否则就创建
    @Test
    public void m3(){
        String directoryPath="d:\\demo\\a\\b\\c";
        File file =new File(directoryPath);
        if(file.exists()){
            System.out.println(directoryPath+"目录已经存在");
        }else{
            System.out.println("目录不存在");
            //创建多级目录用mkdirs  d:\demo\a\b\c
            //创建一级目录用mkdir  d:\demo
            if (file.mkdirs()) {
                System.out.println(directoryPath+"创建成功");
            }else {
                System.out.println(directoryPath+"创建失败");
            }
        }
    }


}

FileInputStream  字节输入流

package com.inputStream;

import org.junit.Test;

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

/**
 * @author lyt
 * @description 演示  FileInputStream的使用(字节输入流  文件-->程序)用于二进制
 *
 * @date 2021/10/12 14:15
 */
public class FileInputStreamCode {
    public static void main(String[] args) {

    }

    /**
     * 演示读取文件
     * 单个字节的读取,效率比较低
     */
    @Test
    public void readFile01(){
        String filePath="d:\\hello.txt";

        int readData=0;
        FileInputStream fileInputStream =null;
        try {
            //创建FileInputStream 对象,用于读取文件
           fileInputStream = new FileInputStream(filePath);
            //从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
            //如何返回-1,表示读取完毕
           while ((readData= fileInputStream.read())!=-1){
               System.out.print((char)readData);//转成char显示
           }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 使用read(byte[]b)读取文件,提高效率
     */
    @Test
    public void readFile02(){
        String filePath="d:\\hello.txt";
        byte[] buf=new byte[8];//一次读取8个字节
        int readLen=0;
        FileInputStream fileInputStream =null;
        try {
            //创建FileInputStream 对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);
            //从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
            //如何返回-1,表示读取完毕
            //如果读取正常,返回实际读取的字节数
            while ((readLen=fileInputStream.read(buf))!=-1){
                System.out.println(new String(buf,0,readLen));//显示
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

FileOutputStream 字节输出流

package com.outPutStream;

import org.junit.Test;

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

/**
 * @author lyt
 * @description
 * @date 2021/10/12 15:12
 */
public class FileOutputStream01 {
    public static void main(String[] args) {

    }

    /**
     * 演示使用FileOutputStream 将数据写到文件中,
     * 如果该文件不存在,则创建该文件
     */
    @Test
    public void writeFile() {

        String filePath = "d:\\b.txt";
        //创建 FileOutputStream对象
        FileOutputStream fileOutputStream = null;
        try {
            //得到FileOutputStream对象 对象
            //1.new FileOutputStream(filePath)创建方式,当写入内容时,会覆盖原来的内容
            //2.new FileOutputStream(filePath,true)创建方式,当写入内容时,是追加到文件后面
            fileOutputStream = new FileOutputStream(filePath,true);
            //写入一个字节
            //fileOutputStream.write('H');
            // 写入字符串
            String str="hhhhhello,world";
            //str.getBytes() 可以把 字符串->字节数组
            //write(byte[] b,int off,int len) 将 len字节从位于偏移量  off的指定字节数组写入此文件输出流
            fileOutputStream.write(str.getBytes(),0,str.length());
            //fileOutputStream.write(str.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

从字节输入流读取文件复制到字节输出流

package com.outPutStream;

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

/**
 * @author lyt
 * @description
 * @date 2021/10/12 15:52
 */
public class FileCopy {
    public static void main(String[] args) {
        //完成 文件拷贝,将 d:\\a.jpg拷贝c:\\
        //思路分析:
        //1.创建文件的输入流,将文件读入到程序
        //2.创建文件的输出流,将读取到的文件数据,写入到指定的文件
        String srcFilePath="d:\\a.jpg";
        String destFilePath="d:\\a\\a.jpg";
        FileInputStream fileInputStream=null;
        FileOutputStream fileOutputStream=null;

        try {
            fileInputStream=new FileInputStream(srcFilePath);
            fileOutputStream=new FileOutputStream(destFilePath);
            //定义一个字节数组,提高读取效率
            byte[] buf=new byte[1024];
            int readLen=0;
            while ((readLen=fileInputStream.read(buf))!=-1){
                 //读取到后,就写入到文件 通过 fileOutputStream
                //即,是一边读,一边写
                fileOutputStream.write(buf,0,readLen);//一定要使用这个方法
            }
            System.out.println("拷贝ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭输入流和输出流
                if (fileInputStream!=null) {
                    fileInputStream.close();
                }
                if(fileOutputStream!=null){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

FileReader  字符

package com.reader;

import org.junit.Test;

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

/**
 * @author lyt
 * @description
 * @date 2021/10/13 10:42
 */
public class FileReaderCode {

    /**
     * 单个字符的读取
     */
    public static void main(String[] args) {
        String filePath = "d:\\hello.txt";
        FileReader fileReader = null;
        int data = 0;
        //1.创建FileReader对象
        try {
            fileReader = new FileReader(filePath);
            //循环读取 使用read,单个字符读取
            while ((data = fileReader.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 字符数组读取
     */
    @Test
    public void readFile(){
        String filePath = "d:\\hello.txt";
        FileReader fileReader = null;
        int readLen=0;
        char[] buf=new char[8];
        //1.创建FileReader对象
        try {
            fileReader = new FileReader(filePath);
            //循环读取 使用read(buf),返回的是实际读取到的字符数
            //如果返回-1,说明到文件结束
            while ((readLen = fileReader.read(buf)) != -1) {
                System.out.print(new String(buf,0,readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

FileWriter  字符

package com.write;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @author lyt
 * @description
 * @date 2021/10/13 11:20
 */
public class FileWriterCode {
    public static void main(String[] args) {
        //创建FileWriter对象
        String filePath="d:\\note.txt";
        FileWriter fileWriter=null;
        char[] chars={'a','b','c'};
        try {
            fileWriter = new FileWriter(filePath);
            //写入单个字符 write(int)
            fileWriter.write('a');
            //写入指定数组 write(char[])
            fileWriter.write(chars);
            //write(char[],off,len) 写入指定数组的指定部分
            fileWriter.write("你好世界".toCharArray(),0,2);
            //write(string)  写入字符串的指定部分
            fileWriter.write("你好呀");
            //write(string,off,len)  写入字符串的指定部分
            fileWriter.write("上海天津",0,2);
            //在数据量大的情况下,可以使用循环操作

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //对应FileWriter,一定要关闭流,或者flush才能真正的把数据写入到文件
            try {
                //fileWriter.flush();
                //关闭文件流,  等价 flush()+关闭
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println("程序结束");
    }
}

Buffer

BufferedReader  字符

package com.buffer;

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

/**
 * @author lyt
 * @description
 * @date 2021/10/13 15:25
 */
public class BufferReader {
    public static void main(String[] args) throws Exception{
        String filePath="d:\\note.txt";
        //创建bufferedReader
        BufferedReader bufferedReader=new BufferedReader(new FileReader(filePath));
        //读取
        String line;
        //说明
        //1.bufferedReader
        while((line=bufferedReader.readLine())!=null){
            System.out.println(line);
        }
        //关闭流,这里注意,只需要关闭
        bufferedReader.close();
    }
}

BufferedWriter 字符

package com.buffer;

import java.io.BufferedWriter;
import java.io.FileWriter;

/**
 * @author lyt
 * @description
 * @date 2021/10/13 15:42
 */
public class BufferWriter {
    public static void main(String[] args) throws Exception{
        String filePath="d:\\ok.txt";
        //创建BufferedWriter
        //new FileWriter(filePath,true) 表示以追加的方式写入
        //new FileWriter(filePath)  表示以覆盖的方式写入
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath,true));
        bufferedWriter.write("hello1,刘");
        bufferedWriter.newLine();//插入一个和系统相关的换行
        bufferedWriter.write("hello2,刘");
        bufferedWriter.write("hello3,刘");
        //插入一个换行

        //说明:关闭外层流即可,传入的new FileWriter(filePath),会在底层关闭
        bufferedWriter.close();
    }
}

BufferedReader   BufferedWriter处理字符的,不处理字节

package com.buffer;

import java.io.*;

/**
 * @author lyt
 * @description  BufferedReader   BufferedWriter处理字符的,不处理字节
 * @date 2021/10/13 16:07
 */
public class BufferCope {
    public static void main(String[] args) {
        //1. BufferedReader   BufferedWriter 是按照字符操作
        //2. 不要去操作二进制文件[声音,视频,word,pdf文件],可能造成文件损坏

        String srcFilePath="d:\\note.txt";
        String destFilePath="d:\\ok.txt";
        BufferedReader br=null;
        BufferedWriter bw=null;
        String line;
        try {
            br = new BufferedReader(new FileReader(srcFilePath));
            bw=new BufferedWriter(new FileWriter(destFilePath));

            //读取  说明:readLine()读取一行内容,但是没有换行
            while((line= br.readLine())!=null){
                //每读取一行,写入
                bw.write(line);
                //插入一个换行
                bw.newLine();
            }
            System.out.println("拷贝完毕");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if(br!=null){
                    br.close();
                }
                if(bw!=null){
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

字节处理流拷贝文件

package demolyt.method;

import java.io.*;

/**
 * @author lyt
 * @version 1.0
 * 演示使用 BufferedInputStream 和 BufferedOutputStream使用
 * 使用他们,可以完成二进制文件拷贝
 * 字节流可以操作二进制文件,可以操作文本文件
 * @date 2021/10/13 21:20
 */
public class Buffer {
    public static void main(String[] args) {
        String srcFilePath = "C:\\Users\\26644\\Documents\\picture";
        String destFilePath = "C:\\Users\\26644\\Documents\\temp";
        //创建
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //因为 FileInputStream  是 InputStream子类
            bis = new BufferedInputStream(new FileInputStream(srcFilePath));
            bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
            //循环读取文件,并写入到destFilePath
            byte[] buf = new byte[1024];
            int readLen = 0;
            //当返回-1时,就表示文件读取完毕
            while ((readLen = bis.read(buf)) != -1) {
                bos.write(buf, 0, readLen);
            }
            System.out.println("读取完毕");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流,关闭外层的处理流即可,底层会去关闭节点流
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

 序列化

package com.outPutStream;

import java.io.Serializable;

/**
 * @author lyt
 * @description
 * @date 2021/10/14 10:36
 */
//如果需要序列化某个类的对象,必须实现Serializable
public class Dog implements Serializable {
    private String name;
    private int age;

    //序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员
    private static String nation;
    private transient String color;

    //序列化对象时,要求里面属性的类型也需要实现序列化接口
    private Master master=new Master();

    //serialVersionUID 序列化的版本号,可以提高兼容性
    public static final long serialVersionUID=1L;

    public Dog(String name, int age,String nation,String color) {
        this.name = name;
        this.age = age;
        this.color=color;
        this.nation=nation;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ",color='"+color+'\''+
                '}'+nation+" "+master;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static void setNation(String nation) {
        Dog.nation = nation;
    }

    public void setColor(String color) {
        this.color = color;
    }
}
package com.outPutStream;

import java.io.Serializable;

/**
 * @author lyt
 * @description
 * @date 2021/10/14 10:53
 */
public class Master implements Serializable {
}
package com.outPutStream;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @author lyt
 * @description 演示ObjectOutStream 的使用,完成数据的序列化
 * 序列化:从Java程序  保存  数据类型和数据对象值 到文件的过程
 * @date 2021/10/14 9:05
 */
public class ObjectOutStream_ {
    public static void main(String[] args) throws Exception {
        //序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
        String filePath = "d:\\data.dat";
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath));
        //序列化数据到:d:\\data.dat
        objectOutputStream.writeInt(100);//int->Integer(实现了Serializable)
        objectOutputStream.writeBoolean(true);//boolean->Boolean(实现了Serializable)
        objectOutputStream.writeChar('a');//char->Character(实现了Serializable)
        objectOutputStream.writeDouble(9.5);//double->Double(实现了Serializable)
        objectOutputStream.writeUTF("教育");//String
        //保存一个dog对象
        objectOutputStream.writeObject(new Dog("阿黄", 12,"中国","白色"));
        objectOutputStream.close();
        System.out.println("数据保存");
    }
}

package com.inputStream;

import com.outPutStream.Dog;

import java.io.*;

/**
 * @author lyt
 * @description 反序列化过程
 * @date 2021/10/14 9:31
 */
public class ObjectInputStream_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //指定反序列化的文件
        String filePath = "d:\\data.dat";
        ObjectInputStream ois= new ObjectInputStream(new FileInputStream(filePath));
        //读取
        //1.读取(反序列化)的顺序需要和你保存数据(序列化)的顺序一致
        //2,否则会出现异常
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readChar());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());

        //dog的编译类型是Object,dog的运行类型是Dog
        Object dog = ois.readObject();
        System.out.println("运行类型="+dog.getClass());
        System.out.println("dog信息="+dog);//底层 Object -> Dog

        //1.如果我们希望调用Dog的方法,需要向下转型
        //2.需要我们将Dog类的定义,拷贝到可以引用的位置
        Dog dog2=(Dog)dog;
        System.out.println(dog2.getName());
        //关闭流  关闭外层流即可,底层关闭FileInputStream流
        ois.close();

    }
}

 System流

package com.standard;

import java.util.Scanner;

/**
 * @author lyt
 * @description
 * @date 2021/10/14 11:07
 */
public class InputAndOutput {
    public static void main(String[] args) {
        // System类的 public final static InputStream in = null;
        // System.in 编译类型 InputStream
        // System.in 运行类型 BufferedInputStream
        // 表示的是标准输入 键盘
        System.out.println(System.in.getClass());//class java.io.BufferedInputStream

        //1.System.out  public final static PrintStream out = null;
        //2.编译类型 PrintStream
        //3.运行类型 PrintStream
        //4.表示标准输出 显示器
        System.out.println(System.out.getClass());//class java.io.PrintStream

        Scanner scanner = new Scanner(System.in);
        String next = scanner.next();
        System.out.println("输出"+next);
    }
}

 转换流:InputStreamReader和、OutputStreamWriter

package com.standard;

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

/**
 * @author lyt
 * @description  转换流-InputStreamReader和、OutputStreamWriter
 * InputStreamReader:Reader的子类,可以将InputStream字节流包装成/转换成Reader字符流
 * OutputStreamWriter:Writer的子类,可以将OutputStream字节流包装成Writer字符流
 * 当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
 * 指定编码格式 utf-8  gbk gb2312 ISO8859-1
 * @date 2021/10/14 13:39
 */
public class CodeQuestion {
    public static void main(String[] args) throws IOException {
        //读取d:\\a.txt 文件到程序
        //思路
        //1.创建字符输入流 BufferedReader[处理流]
        //2.使用BufferedReader 对象读取a.txt
        //3.默认情况下,读取文件是按照utf-8编码
        String filePath="d:\\a.txt";
        BufferedReader br = new BufferedReader(new FileReader(filePath));
        String s = br.readLine();
        System.out.println("读取到的内容"+s);
        br.close();
    }
}

package com.standard;

import java.io.*;

/**
 * @author lyt
 * @description
 * 演示使用InputStreamReader 转换流解决中文乱码问题
 * 将字节流FileInputStream转成字符流 InputStreamReader,指定编码gbk/utf-8
 * @date 2021/10/14 14:01
 */
public class InputStreamReader_ {

    public static void main(String[] args) throws IOException {
        String filePath="d:\\a.txt";
        //1.把FileInputStream 转成 InputStreamReader
//        //2.指定编码 gbk
//        InputStreamReader gbk = new InputStreamReader(new FileInputStream(filePath), "gbk");
//        //3.把InputStreamReader 传入 BufferedReader
//        BufferedReader br = new BufferedReader(gbk);
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "gbk"));
        //4.读取
        String s = br.readLine();
        System.out.println("读取内容="+s);
        //5.关闭外层流
        br.close();
    }

}
package com.standard;

import java.io.*;

/**
 * @author lyt
 * @description
 * 演示OutputStreamWriter 使用
 * 把FileOutputStream 字节流转成字符流OutputStreamWriter
 * 指定处理的编码gbk/utf-8/utf8
 * ANSI就是gbk
 * @date 2021/10/14 14:16
 */
public class OutputStreamWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath="d:\\b.txt";
        String charSet="gbk";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
        osw.write("你好呀");
        osw.close();
        System.out.println("按照"+charSet+"保存成功");
    }
}

PrintWriter 

package com.print;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author lyt
 * @description 字符输出流
 * @date 2021/10/14 15:01
 */
public class PrintWriter_ {
    public static void main(String[] args) throws IOException {
       // PrintWriter printWriter = new PrintWriter(System.out);
        PrintWriter printWriter = new PrintWriter(new FileWriter("d:\\fa.txt"));
        printWriter.print("北极");
        printWriter.close();//flush+关闭流,才会将数据写入到文件
    }
}

PrintStream 

package com.print;

import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;

/**
 * @author lyt
 * @description
 * 演示PrintStream  字节输出打印流
 * @date 2021/10/14 14:44
 */
public class PrintStream_ {
    public static void main(String[] args) throws IOException {
        PrintStream out=System.out;
        //在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
        out.print("aabbcc");
        //因为print底层使用的是write,所以我们可以直接使用write进行打印、输出
        out.write("沃尼塔".getBytes());
        out.close();
        //我们可以去修改打印输出的位置/设备
        //1.修改成到d:\\f1.txt
        //2.输出我呀到d:\\f1.txt
        //3.  public static void setOut(PrintStream out) {
        //        checkIO();
        //        setOut0(out);  //native方法,修改了out
        //    }

        System.setOut(new PrintStream("d:\\f1.txt"));
        System.out.println("我呀");

    }

}

Properties

package com.print;

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

/**
 * @author lyt
 * @description
 * @date 2021/10/14 15:52
 */
public class Properties01 {
    public static void main(String[] args) throws IOException {
        //读取
        BufferedReader br = new BufferedReader(new FileReader("src\\mysql.properties"));
        String line="";
        while((line= br.readLine())!=null){
            String[] split = line.split("=");
            System.out.println(split[0]+" "+split[1]);
        }

    }
}
package com.print;

import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

/**
 * @author lyt
 * @description
 * @date 2021/10/15 8:36
 */
public class Properties02 {
    public static void main(String[] args) throws IOException {
        //使用Properties类来读取mysql.properties文件
        //1.创建Properties对象
        Properties properties = new Properties();
        //2.加载指定配置文件
        properties.load(new FileReader("src\\mysql.properties"));
        //3.把k-v显示控制台
        properties.list(System.out);
        //4.根据key,获取对应的值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        System.out.println("用户名="+user);
        System.out.println("密码="+password);

    }
}
package com.print;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @author lyt
 * @description
 * @date 2021/10/15 8:56
 */
public class Properties03 {
    public static void main(String[] args) throws IOException {
        //使用Properties类来创建配置文件,修改配置文件内容
        Properties properties = new Properties();
        //创建
        //1.如果该文件没有key,就是创建
        //2.如果该文件有key,就是修改
        //Properties   父类是   Hashtable ,底层就是Hashtable 核心方法

        properties.setProperty("charset","utf8");
        properties.setProperty("user","汤姆");//注意保存时,是中文的Unicode码值
        properties.setProperty("pwd","abc111");
        //将k-v存储到文件中即可  null位置表示备注
        properties.store(new FileOutputStream("src\\mysql2.properties"),null);
        System.out.println("保存配置文件成功");
    }
}

 mysql.properties   放在src下

ip=127.0.0.1
user=root
password=123456

练习:

package com.homework;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author lyt
 * @description
 * @date 2021/10/15 9:53
 */
public class Homework01 {
    public static void main(String[] args) throws IOException {
        /**
         * 判断d盘下是否有文件夹mytemp,如果没有就创建mytemp
         * 在d:\\mytemp目录下,创建文件hello.txt
         * 如果hello.txt已经存在,提示该文件已经存在,就不要再重复创建了
         * 并且在hello.txt文件中,写入hello,world~
         */
        String directoryPath="d:\\mytemp";
        File file = new File(directoryPath);
        if(!file.exists()){
            //创建
            if(file.mkdirs()){
                System.out.println("创建"+directoryPath+"创建成功");
            }else{
                System.out.println("创建"+directoryPath+"创建失败");
            }
        }
            String filePath=directoryPath+"\\hello.txt";// d:mytemp\hello.txt
            file = new File(filePath);
            if(!file.exists()){
            //创建文件
                if(file.createNewFile()){
                    System.out.println(filePath+"创建成功~");
                    //如果文件存在,我们就使用BufferedWriter 字符输入流写入内容
                    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
                    bufferedWriter.write("hello,world~~~韩顺平教育");
                    bufferedWriter.close();
                }else{
                    System.out.println(filePath+"创建失败~");
                }
            }else{
                //如果文件已经存在,给出提示信息
                System.out.println(filePath+"已经存在,不在重复创建");
            }

    }
}
package com.homework;

import org.junit.Test;

import java.io.*;

/**
 * @author lyt
 * @description
 * @date 2021/10/15 11:27
 */
public class Homework02 {
    public static void main(String[] args) {
        /**
         * 要求:使用BufferedReader 读取一个文本文件,为每行加上行号,
         * 再连同内容一并输出到屏幕上
         */
        String filePath="d:\\note.txt";
        BufferedReader br=null;
        String line="";
        int lineNum=0;
        try {
            //BufferedReader 处理流
            //FileReader  节点流
             br= new BufferedReader(new FileReader(filePath));
             while((line= br.readLine())!=null){
                 //循环读取
                 System.out.println(++lineNum+" "+line);
             }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(br!=null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    @Test
    public void test(){
        /**
         * 要求:使用BufferedReader 读取一个文本文件,为每行加上行号,
         * 再连同内容一并输出到屏幕上
         * 如果文件的编码格式是gbk,出现中文乱码,思考解决
         * 1.默认是按照utf-8处理,开始没有乱码
         * 2.提示:使用我们的转换流,将FileInputStream->InputStreamReader[可以指定编码]->BufferedReader
         */
        String filePath="d:\\note.txt";
        BufferedReader br=null;
        String line="";
        int lineNum=0;
        try {
            //指定编码gbk  字节流到字符流
            InputStreamReader utf8 = new InputStreamReader(new FileInputStream(filePath), "gbk");
            //BufferedReader 处理流
            //FileReader  节点流
            //InputStreamReader 传入 BufferedReader
            br= new BufferedReader(utf8);
            while((line= br.readLine())!=null){
                //循环读取
                System.out.println(++lineNum+" "+line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(br!=null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
package com.homework;

import org.junit.Test;

import java.io.*;
import java.util.Properties;

/**
 * @author lyt
 * @description
 * @date 2021/10/15 14:26
 *
 * (1)要编写一个dog.properties
 * name=tom
 * age=5
 * color=red
 * (2)编写Dog类(name,age,color)创建一个dog对象,读取dog.properties用相应的内容完成属性初始化,并输出
 * (3)将创建的Dog对象,序列化到文件dog.dat文件
 */
public class Homework03 {
    public static void main(String[] args) throws IOException {
        String filePath = "src\\dog.properties";
        Properties properties = new Properties();
        properties.load(new FileReader(filePath));
        properties.list(System.out);
        String name = properties.get("name") + "";//Object->String
        int age = Integer.parseInt(properties.get("age") + "");//Object->Int
        String color = properties.get("color") + "";//Object->String
        Dog dog = new Dog(name, age, color);
        System.out.println("狗的信息");
        System.out.println(dog);

        //将创建的Dog对象,序列化到文件 dog.dat文件
        String serFilePath = "d:\\dog.dat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFilePath));
        oos.writeObject(dog);
        oos.close();
        System.out.println("dog对象序列化完成");
    }
        //在编写一个方法,反序列化dog
        @Test
        public void m1() throws IOException, ClassNotFoundException {
        String serFilePath="d:\\dog.dat";
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(serFilePath));
            Dog dog =(Dog) ois.readObject();
            ois.close();
            System.out.println("反序列化后");
            System.out.println(dog);
        }

}
class Dog implements Serializable{
    private String name;
    private int age;
    private String color;

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

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }
}

src下的mysql2.properties

#Fri Oct 15 09:23:58 CST 2021
user=\u6C64\u59C6
pwd=abc111
charset=utf8

 src下的dog.properties

name=tom
age=5
color=red
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值