编程语言
首页 > 编程语言> > 第十四话-JavaIO框架

第十四话-JavaIO框架

作者:互联网

分类:

字节流:

字节流的父类(抽象类):

字节流

FileInputStream类

package com.xie.io;

import java.io.FileInputStream;

public class Demo01 {
    public static void main(String[] args) throws Exception {
        //1.创建FileInputStream,并指定文件路径
        FileInputStream fis = new FileInputStream("D:\\java基础\\测试文件\\FileInputStream.txt");
        //2.读取文件,单个字节读取
//        int data = 0;
//        while((data=fis.read())!=-1){
//            System.out.println((char)data);
//        }
        //定义一次读取长度
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count=fis.read(buf))!=-1){
            System.out.println(count);
            System.out.println(new String(buf,0,count));
        }
        fis.close();
        System.out.println("执行结束");
    }
}

FileOutputStream类

package com.xie.io;

import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

public class Demo02 {
    public static void main(String[] args) throws Exception {
        //FileOutputStream构造方法第二个参数为true,则增量输出,不会覆盖原来的内容
        FileOutputStream fos = new FileOutputStream("D:\\java基础\\测试文件\\FileOuputStream.txt",true);
        //单个字符输出
//        fos.write(97);
//        fos.write('b');
//        fos.write('c');
        String str = "Hello World!";
        fos.write(str.getBytes());
        fos.close();
        System.out.println("执行完毕1");
    }
}

字节流复制文件

package com.xie.io;

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

public class Demo03 {
    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("D:\\test.png");
        FileOutputStream fos = new FileOutputStream("D:\\test2.png");
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count=fis.read(buf))!=-1){
            fos.write(buf,0,count);
        }
        fis.close();
        fos.close();
        System.out.println("执行完毕");
    }
}

缓冲流

BufferedInputStream/BufferedOutputStream

BufferedInputStream代码:

package com.xie.io;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

public class Demo04 {
    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("D:\\FileInputStream.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
//        int data = 0;
//        while ((data=bis.read())!=-1){
//            System.out.println((char)data);
//        }
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count=bis.read(buf))!=-1){
            System.out.println(new String(buf,0,count));
        }
        bis.close();
    }
}

BufferedOutputStream代码:

package com.xie.io;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

public class Demo05 {
    public static void main(String[] args) throws Exception {
        FileOutputStream fos = new FileOutputStream("D:\\buffer.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        for (int i = 0; i < 10; i++) {
            bos.write("helloWorld!\r\n".getBytes());
            bos.flush();//刷新到硬盘
        }
        //关闭(会内部调用flush方法)
        bos.close();
    }
}

对象流

ObjectInputStream/ObjectOutputStream

​ writeObject(Objcet obj)向流中写入一个对象

序列化-ObjectOutputStream

package com.xie.io;

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

public class Demo06 {
    public static void main(String[] args) throws Exception {
        FileOutputStream fos = new FileOutputStream("D:\\stu.bin");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        //Student必须实现Serializable接口,作为标记可以序列化
        Student stu1 = new Student("ZHANGSAN",33);
        oos.writeObject(stu1);
        oos.close();
        System.out.println("执行完毕");
    }
}
package com.xie.io;

import java.io.Serializable;

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

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

    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;
    }

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

反序列化-ObjectInputStream

package com.xie.io;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class Demo07 {
    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("D:\\stu.bin");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Student s = (Student)ois.readObject();
        ois.close();
        System.out.println("执行完毕");
        System.out.println(s.toString());
    }
}

注意事项:

private static final long serialVersionUID = 100L;

字符流

字符编码

编码与解码方式不一致,会出现乱码

字符流抽象类

字节流读取汉字,按照字节读取并解析,但是一个汉字三个字节,解析乱码

Reader:字符输入流

Writer:字符输出流

FileReader

package com.xie.io;

import java.io.FileReader;

public class Demo08 {
    public static void main(String[] args) throws Exception{
        FileReader fr = new FileReader("D:\\buffer.txt");
        int data = 0;
        while ((data = fr.read()) != -1){//读取一个字符
            System.out.print((char)data);
        }
        fr.close();
        System.out.println("----------------");
        FileReader fr2 = new FileReader("D:\\buffer.txt");
        int count = 0;
        char[] buf =new char[3];
        while ((count = fr2.read(buf)) != -1){//读取buf的长度,赋值给buf,位置赋值给count
            System.out.println(new String(buf,0,count));
        }
        fr2.close();
    }
}

FileReader

package com.xie.io;

import java.io.FileWriter;

public class Demo09 {
    public static void main(String[] args) throws Exception {
        FileWriter fr = new FileWriter("D:\\buffer.txt");
        for (int i = 0; i < 10; i++) {
            fr.write("java是好语言\r\n");
            fr.flush();
        }
        fr.close();
        System.out.println("执行完毕");
    }
}

字符流复制

package com.xie.io;

import java.io.FileReader;
import java.io.FileWriter;

public class Demo10 {
    public static void main(String[] args) throws Exception{
        //字符流实现文件复制,只能复制文本文件
        FileReader fr = new FileReader("D:\\buffer.txt");
        FileWriter fw = new FileWriter("D:\\buffer2.txt");
        int data = 0;
        while ((data = fr.read()) != -1){
            fw.write(data);
            fw.flush();
        }
        fr.close();
        fw.close();
        System.out.println("执行完毕");
    }
}

字符缓冲流

BufferedReader/BufferedWriter

BufferedReader

package com.xie.io;

import com.xie.oop.demo03.B;

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

public class Demo11 {
    public static void main(String[] args) throws Exception{
        FileReader fr = new FileReader("D:\\buffer.txt");
        BufferedReader br = new BufferedReader(fr);
        char[] buf = new char[1024];
        int count = 0;
        while ((count = br.read(buf)) != -1){
            System.out.println(new String(buf,0,count));
        }
        br.close();
        System.out.println("--------");
        FileReader fr2 = new FileReader("D:\\buffer.txt");
        BufferedReader br2 = new BufferedReader(fr2);
        String line = null;
        while ((line=br2.readLine()) != null){
            System.out.println(line);
        }
        br2.close();
    }
}

BufferedWriter

package com.xie.io;

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

public class Demo12 {
    public static void main(String[] args) throws Exception{
        FileWriter fw = new FileWriter("D:\\buffer.txt");
        BufferedWriter bw = new BufferedWriter(fw);
        for (int i = 0; i < 10; i++) {
            bw.write("好好学习");
            bw.newLine();
            bw.flush();
        }
        bw.close();
        System.out.println("执行完毕");
    }
}

PrintWriter

package com.xie.io;

import java.io.PrintWriter;

public class Demo13 {
    public static void main(String[] args) throws Exception{
        PrintWriter pw = new PrintWriter("D:\\buffer.txt");
        pw.println(97);
        pw.println(true);
        pw.println(3.14);
        pw.println('a');
        pw.close();
        System.out.println("执行完毕");
    }
}

转换流

package com.xie.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Demo14 {
    public static void main(String[] args) throws Exception{
        FileInputStream fi = new FileInputStream("D:\\buffer2.txt");
        InputStreamReader isr = new InputStreamReader(fi,"utf-8");
        int data = 0;
        while ((data = isr.read()) != -1) {
            System.out.print((char)data);
        }
        isr.close();
        System.out.println("------------------");
        FileOutputStream fo = new FileOutputStream("D:\\buffer.txt");
        OutputStreamWriter osw = new OutputStreamWriter(fo,"gbk");
        for (int i = 0; i < 5; i++) {
            osw.write("niho你好\r\n");
            osw.flush();
        }
        osw.close();
        System.out.println("执行完毕");
    }
}

File类

文件、文件夹操作

package com.xie.io;

import java.io.File;
import java.util.Date;

public class Demo15 {
    public static void main(String[] args)  throws Exception{
        //separator();
        //fileOpe();
        dirOpe();
    }
    //分隔符
    public static void separator(){
        System.out.println("路径分隔符" + File.pathSeparator);
        System.out.println("名称分隔符" + File.separator);
    }
    //文件操作
    public static void fileOpe() throws Exception{
        //1.创建文件
        File file = new File("D:\\buffer.txt");
        //System.out.println(file.toString());
        if(!file.exists()){
            boolean b = file.createNewFile();
            System.out.println("创建结果:" + b);
        }
        //2.1删除文件
        //System.out.println("删除结果:" + file.delete());
        //2.2使用jvm退出时删除
//        file.deleteOnExit();
//        Thread.sleep(5000);
        //3获取文件信息
        System.out.println("获取文件的绝对路径" + file.getAbsolutePath());
        System.out.println("获取路径" + file.getPath());
        System.out.println("获取文件名称" + file.getName());
        System.out.println("获取文件长度" + file.length());
        System.out.println("获取文件父目录" + file.getParent());
        System.out.println("文件创建时间" + new Date(file.lastModified()).toLocaleString());
        //4判断
        System.out.println("是否可写:" + file.canWrite());
        System.out.println("是否是文件" + file.isFile());
        System.out.println("是否隐藏" + file.isHidden());
    }

    //文件夹操作
    public static void dirOpe() throws Exception{
        //1.创建文件夹
        File dir = new File("D:\\aaa\\bbb\\ccc");
        System.out.println(dir.toString());
        if(!dir.exists()){
            //dir.mkdir();//只能创建单级目录
            System.out.println("创建结果:" + dir.mkdirs());//创建多级目录

        }
        //2.删除文件夹,注:只能删除单个文件夹。只能删除空文件夹
        //System.out.println("删除结果:" + dir.delete());//直接删除
        //dir.deleteOnExit();//使用jvm删除
        //Thread.sleep(5000);
        //3.获取文件夹信息
        System.out.println("获取绝对路径:" + dir.getAbsolutePath());
        System.out.println("获取路径:" + dir.getPath());
        System.out.println("获取文件夹名称:" + dir.getName());
        System.out.println("获取父目录:" + dir.getParent());
        System.out.println("获取创建时间:" + new Date(dir.lastModified()).toLocaleString());
        //4.判断
        System.out.println("是否是文件夹:" + dir.isDirectory());
        System.out.println("是否隐藏" + dir.isHidden());
        //5.遍历文件夹
        File dir2 = new File("D:\\apache-tomcat-9.0");
        String[] files = dir2.list();
        for (String file : files) {
            System.out.println(file);
        }
    }
}

FileFilter接口

package com.xie.io;

import java.io.File;
import java.io.FileFilter;

public class Demo16 {
    public static void main(String[] args) {
        File dir2 = new File("D:\\apache-tomcat-9.0");
        File[] files =  dir2.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if(pathname.getName().endsWith(".txt")){
                    return true;
                }
                return false;
            }
        });
        for (File file : files) {
            System.out.println(file.getName());
        }
    }
}

递归遍历、删除

package com.xie.io;

import java.io.File;

public class Demo17 {
    public static void main(String[] args) {
        listDir(new File("D:\\BaiduNetdiskDownload"));
        deleteDir(new File("D:\\aaa"));
    }
    //遍历文件夹
    public static void listDir(File dir){
        File[] files = dir.listFiles();
        System.out.println(dir.getAbsolutePath());
        if(files != null && files.length> 0 ){
            for (File file : files) {
                if(file.isDirectory()){
                    listDir(file);
                }else {
                    System.out.println(file.getAbsolutePath());
                }
            }
        }
    }
    //遍历删除文件夹
    public static void deleteDir(File dir){
        File[] files = dir.listFiles();
        if(files != null && files.length> 0 ){
            for (File file : files) {
                if(file.isDirectory()){
                    deleteDir(file);
                }else {
                    System.out.println(file.getAbsolutePath()+"--删除:"+file.delete());
                }
            }
        }
        System.out.println(dir.getAbsolutePath()+"删除:"+dir.delete());
    }
}

Properties

package com.xie.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.Set;

public class Demo18 {
    public static void main(String[] args) throws Exception{
        Properties properties = new Properties();
        properties.setProperty("username","zhangsan");
        properties.setProperty("age","33");
        System.out.println(properties);
        //遍历
        //1.keySet遍历
        //2.entrySet遍历
        //3.stringPropertyNames()遍历
        Set<String> pronames = properties.stringPropertyNames();
        for (String proname : pronames) {
            System.out.println(proname+"----"+properties.getProperty(proname));
        }
        //和流有关的方法
        //1. list()打印
        PrintWriter pw = new PrintWriter("d:\\print.txt");
        properties.list(pw);
        pw.close();
        //2. store()保存
        FileOutputStream fos = new FileOutputStream("d:\\store.properties");
        properties.store(fos,"zhushi");
        fos.close();
        //3. load()加载
        Properties properties1 = new Properties();
        FileInputStream fis = new FileInputStream("d:\\store.properties");
        properties1.load(fis);
        fis.close();
        System.out.println(properties1);
    }
}

标签:框架,System,JavaIO,io,第十四,println,new,public,out
来源: https://www.cnblogs.com/xiexieyc/p/16181599.html