Java IO stream practice

Posted by ol4pr0 on Mon, 17 Jan 2022 11:20:24 +0100

File Exclusive

java.io.FileInputStream;

java.io.FileOutputStream;


java.io.FileReader;

java.io.FileWriter;

You should construct an array of basic data types to read and write, such as char[] int []
The first two streams process bytes, which can process text documents (all files that can be opened by WordPad), photos, videos, audio, etc.
It should be noted that when Stream writes a file, it should assign the file directory to the specific file name, otherwise access will be denied

Then, each time the file is processed, for example, when new content is written, the file should be refreshed - flush()
In the try statement, finally judge whether the file is empty at finally. If it is not empty, close the file, otherwise it will occupy too much memory.

FileInputStream-FileOutputStream

Byte stream

package com.hdujavaTest.IOTest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
/*File Exclusive
* Reading byte stream can not only process text documents, but also read and write images and other formats, because the bottom layer processes bytes
*
* */
public class FileInputStreamTest01 {
    public static void main(String[] args) {
        //File byte input stream reads file
        String txt="C:\\Users\\wish_cai\\Pictures\\university\\psb.jpg";
        fileInputStreamfuntion(txt);

        //File write
        /*String txtwrite="D:\\JAVA\\java_test\\IOTest02.txt";
        fileOutputStreamfuntion(txtwrite);*/

        //Copying text documents is OK, but access is denied if pictures are involved
        //The previous replication is FileOutputStream, which involves the folder path C:\Users\wish_cai\Pictures \ job, and FileOutputStream is written to a file, so it needs to be to the specific file name
        String txtwritecopy="C:\\Users\\wish_cai\\Pictures\\task\\New text document.jpg";
        fileCopy(txt,txtwritecopy);
    }
    //Read input hard disk to memory
    public static String fileInputStreamfuntion(String txt){
        //The default path of idea is under Project
        //If the file is under another module, the module \ \ SRC (according to the actual) \ \ file name should be read
        //Document byte input stream
        String s=null;
        FileInputStream fileInputStream=null;
        try{
            /*read()Read one byte at a time and return as int*/
            /*
            System.out.println("Read one byte at a time and return ")" in the form of int;
            fileInputStream=new FileInputStream(txt);
            int filer;
            while ((filer=fileInputStream.read())!=-1){
                System.out.print(filer+" ");
            }
            */

            /*Set a byte array, read bytes with read(byte []), and return the quantity*/
            //After reading, you need to create a FileInputStream object again
            //When the last array is not enough, the previous array will be overwritten, and the later array will still be retained
            /*
            System.out.println('\n'+"Set a byte array, read bytes with read(byte []), and return the quantity: ";
            fileInputStream=new FileInputStream(txt);
            byte[] bytesarr=new byte[6];
            int num;
            while ((num=fileInputStream.read(bytesarr))!=-1){
                //System.out.println(num);
                String s=new String(bytesarr,0,num);
                System.out.print(s);
                //System.out.print(new String(bytesarr,0,num));
            }
             */

            //.available();// Indicates how many bytes are available
            //System.out.println('\n' + "indicates how many bytes are available");
            fileInputStream=new FileInputStream(txt);
            //fileInputStream.available();// Indicates how many bytes are available
            System.out.println(fileInputStream.available());
            byte[] bytesarr2=new byte[fileInputStream.available()];
            fileInputStream.read(bytesarr2);
            String s2=new String(bytesarr2,0,bytesarr2.length);
            //System.out.println(s2);
            s=s2;

            //How many bytes are skipped
           /* System.out.println("How many bytes are skipped ");
            fileInputStream=new FileInputStream(txt);
            fileInputStream.skip(8);
            byte[] bytesarr3=new byte[fileInputStream.available()];
            fileInputStream.read(bytesarr3);
            String s3=new String(bytesarr3,0,bytesarr3.length);
            System.out.println(s3);*/

            //
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileInputStream!=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return s;
    }

    //Write output memory to hard disk. txt is our path here
    public static void fileOutputStreamfuntion(String txt){

        FileOutputStream fileOutputStream=null;
        try{
            //Use with caution. If a file does not exist, it will automatically create a new path and content. If a file exists before, it will overwrite the original content
            fileOutputStream=new FileOutputStream(txt);
            System.out.println("Enter what needs to be written:");
            Scanner scanner=new Scanner(System.in);
            String s=scanner.next();
            //String s="xinjianyigwenjianj.tsg";
            //s.getBytes(); Convert to byte array
            fileOutputStream.write(s.getBytes());

            //Append write
            fileOutputStream=new FileOutputStream(txt,true);
            System.out.println("Append write input the content to be written:");
            Scanner scanner1=new Scanner(System.in);
            String s2=scanner1.next();
            //String s="xinjianyigwenjianj.tsg";
            //s.getBytes(); Convert to byte array
            fileOutputStream.write(s2.getBytes());

            //Add in front
            //If there is no shortcut key, my idea is to read the previous file first, then write the one I want to add at the beginning, and then write the previous one

            //Refresh after writing
            fileOutputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileOutputStream!=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //Copy of files
    public static void fileCopy(String txtread,String txtwrite){
        FileInputStream fileInputStream=null;
        FileOutputStream fileOutputStream=null;
        try{
            //Enter a stream object first
            fileInputStream=new FileInputStream(txtread);//read
            fileOutputStream=new FileOutputStream(txtwrite);//write

            //Then read and write
            int r;
            byte[] bytes=new byte[1024*1024];
            while ((r=fileInputStream.read(bytes))!=-1){
                fileOutputStream.write(bytes,0,r);
            }
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileInputStream!=null){
                try{
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fileOutputStream!=null){
                try{
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

FileReader-FileWriter

Character stream
Read text file with character stream
But only text documents can be processed

package com.hdujavaTest.IOTest;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/*File Exclusive
 Read the text file with character stream (which can be opened with Notepad) and copy the text file
 But only text documents can be processed
* */
public class Fileread01 {
    public static void main(String[] args) {
        /*String txt="D:\\JAVA\\java_test\\IOTest04copy.txt";
        FileReadfun(txt);*/

        /*String txt1="C:\\Users\\wish_cai\\Pictures\\Jobs \ \ write12 txt";
        FileWriterfun(txt1);*/

        String txt="D:\\JAVA\\java_test\\IOTest04copy.txt";
        String tet2="D:\\JAVA\\java_test\\IOrTow001.txt";
        CopyFile(txt,tet2);
    }

    public static void FileReadfun(String txt){
        FileReader fileReader=null;
        try{
            fileReader=new FileReader(txt);
            char[] chars=new char[30];
            int readnum;
            fileReader.read(chars);
            for (char c:chars) {
                System.out.print(c);
            }

            fileReader=new FileReader(txt);
            char[] chars2=new char[30];
            while ((readnum=fileReader.read(chars2))!=-1){
                System.out.println(new String(chars2,0,readnum));
            }

            fileReader=new FileReader(txt);
            while ((readnum=fileReader.read())!=-1){
                System.out.println(readnum);
            }

            fileReader=new FileReader(txt);

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

    //Only plain text can be written because characters are processed and bytes are processed in the preceding stream
    public static void FileWriterfun(String txt){
        FileWriter fileWriter=null;
        try{
            fileWriter=new FileWriter(txt);
            System.out.println("input need your contents");
            Scanner scanner=new Scanner(System.in);
            String x=scanner.nextLine();
            fileWriter.write(x);
            fileWriter.flush();
            FileReadfun(txt);//You cannot read until you refresh
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileWriter!=null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //Copy can only copy ordinary text, read it first and then write it
    public static void CopyFile(String readtxt,String writetxt){
        FileReader fileReader=null;
        FileWriter fileWriter=null;
        try{
            fileReader=new FileReader(readtxt);
            fileWriter=new FileWriter(writetxt);

            char[] rTow=new char[30];
            int numread=0;
            while ((numread=fileReader.read(rTow))!=-1){
                fileWriter.write(rTow);
            }
            fileWriter.close();

            FileReadfun(writetxt);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

}

Conversion flow

Convert byte stream to character stream

When the buffer stream is used later
We don't have to customize the array to assist reading and writing
The parameters of the buffer flow construction method are

 public BufferedReader(Reader in) {
        this(in, defaultCharBufferSize);
    }
public BufferedWriter(Writer out) {
        this(out, defaultCharBufferSize);
    }

It can be seen that the types are Reader and Writer. In character stream and byte stream, only character stream FileWriter and FileReader are consistent.
If we want to pass in the byte stream in the constructor parameter of the buffer stream, we need to use the conversion stream

OutputStreamWriter(new FileOutputStream("txt"))
InputStreamReader(new FileInputStream("txt"));

Buffer stream bufferedwriter BufferedReader

**
Buffer stream exclusive

  • There is no need to customize char array and byte array, with its own buffer
  • Pass the class FileReader under character stream -- Reader into the constructor of wrapper stream
  • FileReader extends InputStreamReader ;;;;; InputStreamReader extends Reader
  • If it is a byte stream, how does FileInputStream pass in
  • Convert by conversion stream
  • You can read it line by line
    **
package com.hdujavaTest.IOTest;

import java.io.*;


/*
* Buffer stream exclusive
* There is no need to customize char array and byte array, with its own buffer
* Pass the class FileReader under character stream -- Reader into the constructor of wrapper stream
* FileReader extends InputStreamReader         ;;;;; InputStreamReader extends Reader
*
* If it is a byte stream, how does FileInputStream pass in
* Convert by conversion stream
 * You can read it line by line
* */
public class Buffered01 {
    public static void main(String[] args) throws IOException {
        //Buffered stream reads do not need to construct a specific array
        String txt="D:\\JAVA\\java_test\\IOTest\\out\\production\\IOTest\\com\\hdujavaTest\\IOTest\\Fileread01.class";
        Bufferread(txt);

        //Buffer stream writes do not need to construct a specific array
        String txtwrite="C:\\Users\\wish_cai\\Pictures\\task\\tete.txt";
        Bufferwirte(txtwrite);
    }

    public static void Bufferread(String txt) throws IOException {
        //Characters are passed into the buffer stream

        BufferedReader bufferedReader=null;
        FileReader fileReader=new FileReader(txt);
        bufferedReader=new BufferedReader(fileReader);
        //String x=bufferedReader.readLine();
        String x;
        while ((x=bufferedReader.readLine())!=null){
            System.out.println(x);
        }
        bufferedReader.close();

        //Bytes are passed into the buffered stream through the transformed stream
        FileInputStream in=new FileInputStream(txt);//********Byte stream
        InputStreamReader inputStreamReader=new InputStreamReader(in);//***********Convert stream to character stream by conversion
        BufferedReader bufferedReader1=null;
        bufferedReader1=new BufferedReader(inputStreamReader);//*****Incoming
        bufferedReader1.close();
        /*In the constructor parameter after new is a node flow
        * With which construction method, its reference is a wrapper flow
        * */
        
        /*Merge write*/
        BufferedReader bufferedReader2=new BufferedReader((new InputStreamReader(new FileInputStream(txt))));
    }

    public static void Bufferwirte(String txt) throws IOException {
        BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter(txt));//Character stream
        bufferedWriter.write("qweqhuiwfhais.!!!");
        //Remember to refresh when making changes to the file
        bufferedWriter.flush();
        bufferedWriter.close();

        /*Conversion flow*/
        BufferedWriter bufferedWriter1=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(txt,true)));//true append
        bufferedWriter1.write("\n"+"1111111111");
        bufferedWriter1.flush();
        bufferedWriter1.close();

    }
}

Data flow exclusive

Ability to save data type + actual content
And can only be read and written with the corresponding data stream
DataOutputStream

package com.hdujavaTest.IOTest;

import java.io.*;

public class DataStream01 {
    public static void main(String[] args) throws IOException {
        String txt1="D:\\bilibili\\JJDown\\Download\\Java Zero basics tutorial video (for Java 0 Basics, Java Beginner (Introduction)\\Data)";
        DataOutputStream(txt1);

        DataInputStream(txt1);
    }

    //Data byte input stream with basic data type
    //And can only be opened through the corresponding DataInputstream
    public static void DataOutputStream(String txt) throws IOException {
        DataOutputStream dataOutputStream=new DataOutputStream(new FileOutputStream(txt));
        int a=1;
        int b=2;

        dataOutputStream.writeInt(a);
        dataOutputStream.writeInt(b);
        dataOutputStream.flush();
        dataOutputStream.close();
    }

    //Read exclusive data stream
    //And know its special order
    public static void DataInputStream(String txt) throws IOException {
        DataInputStream dataInputStream=new DataInputStream(new FileInputStream(txt));
        int x=dataInputStream.readInt();
        int y=dataInputStream.readInt();

        System.out.println(x);
        System.out.println(y);
    }
}

Standard output stream

Write directly to file

package com.hdujavaTest.IOTest;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
//No need to close manually
public class PrintStream01 {
    public static void main(String[] args) throws FileNotFoundException {
        System.out.println("Standard output stream—— print");
        PrintStream ps=System.out;
        ps.println("adsad");
        ps.println(1);
        ps.println(true);

        //Write to a fixed path file
        PrintStream ps1=new PrintStream(new FileOutputStream("D:\\bilibili\\JJDown\\Download\\Java Zero basics tutorial video (for Java 0 Basics, Java Beginner (Introduction)\\ad"));
        ps1.println(11111);
        ps1.println("ahuidqaas");
    }
}

File class

File has nothing to do with the four families, so file cannot read and write files
*What does the File object represent?

  • C:\ddd
  • C:\dasdf\asf\asfasf\asfa.txt
  • The File object may be a corresponding directory or a File
  • File is just an abstract representation of a path
    It is also very convenient for file processing.
    It can judge whether the file path exists, create a new one if it does not exist, return the last modified time, delete the file path, return the absolute form of the path, return the file name, return the file names of all sub files (listFiles), etc.
public class File01 {
    public static void main(String[] args) {
        File file=new File("C:\\Users\\wish_cai\\Pictures\\task\\");
        System.out.println("Whether the file exists:"+file.exists());
        System.out.println(file.length());
        //New as file does not exist
        File file1=new File("C:\\Users\\wish_cai\\Pictures\\task\\xinjian");
        if(!file1.exists()) {
            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        File file2=new File("C:\\Users\\wish_cai\\Pictures\\a\\b\\c\\");
        if(!file2.exists())
            file2.mkdirs();//mkdirs creates multiple directories. Otherwise, only one mkdir can be created. Without s, multiple directories will not be created.
    }
}

File copy

java|IO stream to realize file copy

package com.hdujavaTest.IOTest;

import java.io.*;

/**
 *Problem 1: after getting the directory of the subfolder, because FileInputStream needs to read the file name, it denies access -- recursive call
 * Involves creating a new directory
 *
 * */
public class CopyFile01 {
    public static void main(String[] args) {
        File filesrc=new File("C:\\Users\\wish_cai\\Pictures\\task");
        File filedest=new File("D:\\bilibili\\JJDown\\Download\\Java Zero basics tutorial video (for Java 0 Basics, Java Beginner (Introduction)\\copy\\");
        CopyDir(filesrc,filedest);
    }

    private static void CopyDir(File filesrc, File filedest){
        if(filesrc.isFile()){
            //Copy the file first, and then jump out of the recursion. Otherwise, it is the directory and enter the directory operation.
            //System.out.println(filesrc.getAbsolutePath());
            //If it is a file, copy it
            copyfile(filesrc,filedest);
            return;
        }
        File temFile=null;

        File[] files=filesrc.listFiles();
        for (File f:files) {//File or directory

            File newdest=null;
            File newsrc=null;

            if(f.isDirectory()){
                /*Enter when f is a subdirectory in the directory*/
                String name=f.getName();
                String destDir=filedest.getAbsolutePath().endsWith("\\")?(filedest.getAbsolutePath()+name):(filedest.getAbsolutePath()+"\\"+name);
                /*System.out.println(destDir);*/
                //Generate a new directory in the copy path
                newdest=new File(destDir);
                if(!newdest.exists())
                    newdest.mkdirs();

                /*String srcDir=f.getAbsolutePath().endsWith("\\")?f.getAbsolutePath():(f.getAbsolutePath()+"\\");*/
                String srcDir=f.getAbsolutePath();
                System.out.println(srcDir);
                newsrc=new File(srcDir);
                temFile=newdest;//Update copy path
                CopyDir(newsrc,temFile);

            }
            //temFile=newdest;
            /*When there is a file in the directory, enter the next cycle, and then copy it directly*/
            if(!(f.isDirectory())){
                CopyDir(f,filedest);
            }

        }
    }

   private static void copyfile(File src,File dest){
        FileInputStream fileInputStream=null;
        FileOutputStream fileOutputStream=null;
        String txt=dest.getAbsolutePath().endsWith("\\")?dest.getAbsolutePath():(dest.getAbsolutePath()+"\\")+src.getName();
       System.out.println(txt);
        try{
            fileInputStream=new FileInputStream(src);
            fileOutputStream=new FileOutputStream(txt);

            byte[] bytes=new byte[1024*1024];
            int readcount;
            while ((readcount=fileInputStream.read(bytes))!=-1){
                fileOutputStream.write(bytes,0,readcount);
            }

            fileOutputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileInputStream!=null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fileOutputStream!=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
   }
}

Topics: Java