【java】javaSE知识梳理-文件

文件氛围文本文件和非文本文件,非本文文件只能使用字节流读写。

java.io.File类是处理文件非内容的类

对应类code

package javaIO.file.constructor;

import org.junit.Test;

import java.io.File;

/**
 * @file类的构造器
 * @author ChenDan
 * @create 2021-05-23
 */
public class ConstructorsTest {
    String pathName1 = "xx2.txt";
    String pathName2 = "/Users/chendan/IdeaProjects/untitled/javaSE/";
    String pathName3 = "/Users/chendan/IdeaProjects/untitled/javaSE/xx2.txt";

    File file1,file2,file3;

    /**
     * File类的构造器
 * public File(String pathname)
 * public File(String parent, String child)
     */
    @Test
    public void contructorsTest() {
        String pathName1 = "xx2.txt";
        String pathName2 = "/Users/chendan/IdeaProjects/untitled/javaSE/xx2.txt";
        String pathName3 = "/Users/chendan/IdeaProjects/untitled/javaSE/";

        file1 = new File(pathName1);  // 文件名
        file2 = new File(pathName2);  // 路径
        file3 = new File(pathName3,pathName1); // 路径+文件名

        System.out.println(file1);
        System.out.println(file2);
        System.out.println(file3);
    }

}
View Code

处理文件流归类如下:

抽象基类

package javaIO.file.methods;

import org.junit.Test;

import java.io.*;
import java.util.Arrays;

/**
 * @desc 调用虚基类的派生类,读取+写入文件
 * @author ChenDan
 * @create 2021-05-31
 */
public class InputStreamOutputStreamReaderWrite {
    File f = new File("xx.txt");
    File f1 = new File("xx1.txt");
    File ff = new File("xx.png");
    File ff1 = new File("xx1.png");

    /**
     * 字节流
     */
    @Test
    public void InputStreamOutStreamTest() {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(ff);
            os = new FileOutputStream(ff1);

            // 方法一:int read()
            int data;
            while((data = is.read()) != -1) {
                os.write(data);
                System.out.print((char)data);
            }

            // 方法二:int read(byte b[])
            byte[] b = new byte[5];
            while((is.read(b)) != -1){
                os.write(b);
                System.out.println(Arrays.toString(b));
            }

            // 方法三:int read(byte b[], int off, int len)  // 图片视频这种方法可能读取的是无效的
            byte[] b2 = new byte[500];
            while((is.read(b2,30,5)) != -1) {
                os.write(b2);
                System.out.println(Arrays.toString(b2));
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 字符流
     */
    @Test
    public void ReaderWriteTest() {
        Reader r = null;
        Writer w = null;
        try {
            r = new FileReader(f);
            w = new FileWriter(f1);

            // 方法一:一字节一字节读+写
//            int data;
//            while((data = r.read()) != -1) {
//                w.write(data);
//                System.out.print((char)data);
//            }

            // 方法二:五字节五字节读+写
//            char[] cubf = new char[5];
//            while((r.read(cubf)) != -1) {
//                w.write(cubf);
//                System.out.println(Arrays.toString(cubf));
//            }

            // 方法三:按照需求片段读+写
//            char[] cubf1 = new char[5];
//            while((r.read(cubf1)) != -1) {
//                w.write(cubf1,3,2);  // off:起始字节,len:截取长度
//                System.out.println(Arrays.toString(cubf1));
//            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(r != null) {
                try {
                    r.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(w != null) {
                try {
                    w.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
View Code

IO流

package javaIO.file.methods;

import org.junit.Test;

import java.io.*;

/**
 * @author ChenDan
 * @create 2021-05-26
 * @desc 流的分类
 * 操作数据单位:字节流(8bit-图片等)+字符流(16bit-文本)
 * 数据的流向:输入+输出
 * 流的角色:节点流(直接作用在文件之上)+处理流(文件之上包装)
 */
public class FileReaderOrInputStream {
    File file = new File("xx.txt");
    File fileCopy = new File("xx4.txt");
    File file1 = new File("xx.png");
    File fileCopy1 = new File("xx4.png");

    /**
     * IO流练习,字节流
 * FileInputStream 输入流
     * 创建:FileInputStream fr
         * public FileInputStream(File file) throws FileNotFoundException
         * 该文件必须存在,不然会报异常
     * 使用:fis.read():public int read() throws IOException
         * public int read(byte b[]) throws IOException 读取数组 - byte
     * 关闭:fis.close():public void close() throws IOException
 * FileOutputStream 输出流
     * 创建:FileOutputStream fos
     * public FileOutputStream(File file, boolean append) throws FileNotFoundException
     * append=true,保留原文件信息,在文件结尾开始写入
     * 使用:public void write(int c) throws IOException
         * public void write(byte b[]) throws IOException 读取数组 -byte
     * 关闭:public void close() throws IOException
     */
    @Test
    public void test1() {
        long start = System.currentTimeMillis();

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(file1);  // 该文件必须存在,不然会报异常
            fos = new FileOutputStream(fileCopy1,false); // 默认不覆盖,字符串可以,但是要是文件/图片什么的就不行了

//            byte[] cbuf = new byte[9000];
//            while((fis.read(cbuf))!=-1) {
////                System.out.println(Arrays.toString(cbuf));
//                fos.write(cbuf);
//            }
            fos.write("2".getBytes());
            fos.write("2dksnaldkn".getBytes());

//            int data;
//            while((data = fis.read())!=-1){
//                fos.write(data);
//                System.out.print((char)data);
//            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if(fis != null) {
                fis.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if(fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("文件字节流复制时常:"+ (end - start));
    }

    /**
     * IO流练习,字符流
 * FileReader 输入流
     * 创建:FileReader fr:
         * public FileReader(File file) throws FileNotFoundException
         * public FileWriter(File file, boolean append) throws IOException
             * append=true,不覆盖原文件内容
     * 使用:fr.read():public int read() throws IOException
         * public int read(char cbuf[]) throws IOException 读取数组 - char
     * 关闭:fr.close():public void close() throws IOException
 * FileWriter 输出流
     * 创建:FileWriter fw
     * 使用:public void write(int c) throws IOException
         * public FileWriter(File file) throws IOException 读取数组 - char
     * 关闭:public void close() throws IOException
     */
    @Test
    public void test() {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            fr = new FileReader(file);
            fw = new FileWriter(fileCopy,true);

            int data;
            while((data = fr.read())!=-1){
                fw.write(data);
                System.out.print((char)data);
            }

            char[] cbuf = new char[5];
            while((fr.read(cbuf))!=-1) {
                fw.write(cbuf);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if(fr != null) {
                fr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if(fw != null) {
                fw.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
View Code

缓冲流

package javaIO.file.methods;

import org.junit.Test;

import java.io.*;

/**
 * @author ChenDan
 * @create 2021-05-27
 * @desc 缓冲流
 */
public class BufferReaderOrImputStream {
    File file = new File("xx.txt");
    File fileCopy = new File("xx4.txt");
    File file1 = new File("xx.png");
    File fileCopy1 = new File("xx4.png");

    /**
     * 缓冲流:字节流
     * public BufferedInputStream(InputStream in)
     * public BufferedOutputStream(OutputStream out)
     */
    @Test
    public void testInput() {
        long start = System.currentTimeMillis();

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try{
            bis = new BufferedInputStream(new FileInputStream(file1));
            bos = new BufferedOutputStream(new FileOutputStream(fileCopy1));

//            int data;
//            while((data = bis.read()) != -1) {
//                System.out.println(data);
//                bos.write(data);
//            }

            byte[] cubf = new byte[5];
            while((bis.read(cubf))!=-1){
//                System.out.println(Arrays.toString(cubf));
                bos.write(cubf);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("缓冲流+字节流复制时常:"+ (end - start));
    }

    /**
     * 缓冲流:字符流
         * 查询多出:public String readLine() throws IOException
     */
    @Test
    public void testReader() {
        FileReader fr = null;
        FileWriter fw = null;
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            fr = new FileReader(file);
            fw = new FileWriter(fileCopy);

            br = new BufferedReader(fr);
            bw = new BufferedWriter(fw);

//            int data;
//            while ((data = br.read()) != -1) {
//                System.out.print((char)data);
//                bw.write(data);
//            }

//            char[] cubf = new char[5];
//            while((br.read(cubf))!=-1){
//                System.out.println(Arrays.toString(cubf));
//                bw.write(cubf);
//            }

            // 独特方法:一行一行读取
            String data;
            while((data = br.readLine()) != null) {
                System.out.println(data);
                bw.write(data);
            }

        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



}
View Code

转换流

package javaIO.file.methods;

import org.junit.Test;

import java.io.*;

/**
 * @desc 字符流-字节流转换
     * 编码+解码
     * ASCII:美国标准信息交换码
     * ISO8895-1:欧洲码表
     * GBK-中文:<=2字节
     * Unicode:国标码-所有信息,2字节
     * UTF-8:1-4字节
 * @author ChenDan
 * @create 2021-05-27
 */
public class InputStreamReaderTest {
    File file = new File("xx.txt");
    File fileCopy = new File("xx4.txt");
//    File file = new File("xx.png");
//    File fileCopy = new File("xx4.png");

    /**
     *     public InputStreamReader(InputStream in, String charsetName)
     */
    @Test
    public void test() {
        InputStreamReader isr =null;
        OutputStreamWriter osw = null;
        try {
            isr = new InputStreamReader(new FileInputStream(file),"gbk");
            osw = new OutputStreamWriter(new FileOutputStream(fileCopy));

            int data;
            while ((data = isr.read()) != -1){
                System.out.print((char)data);
                osw.write(data);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
View Code

打印流+数据流

package javaIO.file.methods;

import org.junit.Test;

import java.io.*;

/**
 * @author ChenDan
 * @create 2021-05-27
 * @desc 其他流
 * 输出+输出流:
     * System.in:控控制台输入
     * System.out:控制台输出
 */
public class OtherStream {
    public static void main(String[] args) {
    }

    /**
     * 数据流:DataOutputStream+DataIutputStream
     * 用于读取或写出基本类型的变量/字符串
     * public final void writeXxx(T t) throws IOException:写入对应数据类型的信息
     * public void flush() throws IOException :刷新,写入变量
     * public final int readXxx() throws IOException:读书对应数据类型的信息(按照写入的顺序读)
     */
    @Test
    public void test1() {
        try {
            DataOutputStream dos = new DataOutputStream(new FileOutputStream("xx.txt"));
            dos.writeUTF("傻子");
            dos.flush(); // 刷新操作,将内存中的数据写入文件
            dos.writeInt(89);
            dos.flush();
            dos.writeBoolean(false);
            dos.flush();
            dos.close(); // 数据流关闭
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            DataInputStream dis = new DataInputStream(new FileInputStream("xx.txt"));
            System.out.println(dis.readUTF());
            System.out.println(dis.readInt());
            System.out.println(dis.readBoolean());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 打印流:PrintStream+PrintWriter
     * public PrintStream(OutputStream out, boolean autoFlush)
     * public static void setOut(PrintStream out):将本应该控制台输出的文件变相输出
     */
    @Test
    public void test() {

        PrintStream ps = null;
        try{
            FileOutputStream fos = new FileOutputStream(new File("xx.txt"));

            ps = new PrintStream(fos,true);
            if(ps!=null) {
                System.setOut(ps);
            }

            for (int i = 0; i < 255; i++) {
                System.out.println((char)i);
                if(i%50==0){
                    System.out.println();
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if(ps!=null) {
                ps.close();
            }
        }
    }

    /**
     * 控制台输入/输出:System.in+System.out
     * public InputStreamReader(InputStream in)
     */
    @Test
    public void Systemtest() {
        BufferedReader br = null;
        try{
            InputStreamReader isr = new InputStreamReader(System.in);
            System.out.println("fehfjd");
            br = new BufferedReader(isr);

            while(true){
                System.out.println("请输入字符串:");
                String data = br.readLine();
                if("e".equals(data) || "exit".equals(data)){
                    System.out.println("程序结束");
                    break;
                }
                String upperCase = data.toUpperCase();
                System.out.println(upperCase);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
View Code

 

posted @ 2021-05-31 19:51  cdan134  阅读(44)  评论(0)    收藏  举报