Read and write operations of java files

java IO

Read and write operations of java files

The previous blog mentioned the concepts of File class and stream. This blog will introduce the specific usage in detail:

InputStream and FileInputStream

Common methods of InputStream and FileInputStream
  • Common methods of InputStream class

    int read() reads byte by byte from the input stream and returns the integer representation of the byte. If it reaches the end of the input stream, it returns - 1

    int read(byte[] b) reads a number of bytes from the input stream, saves these bytes to array B, and returns the number of bytes read. If it reaches the end of the input stream, it returns - 1

    Int read (byte [] b, int off, int len) reads several bytes from the input stream and saves them in array b. Off refers to the starting subscript in the byte array to save data, len refers to the number of bytes read, and returns the number of bytes actually read. If the end of the input stream is read, it returns - 1

    void close(): close the input stream

    int available(): the number of bytes that can be read from the input stream

InputStream is an abstract base class. Its subclass FileInputStream is required to create an object.

  • Common construction methods of subclass FileInputStream

    FileInputStream(File file)

    FileInputStream(String pathname)

Example

The premise is: create a test. In the current project Txt file, write a string of text from it, save and exit

package Test;
//1. Introduce relevant flows

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

//Read the file through the byte input stream
public class FileInputStreamDemoTest {
    public static void main(String[] args) {
        FileInputStream fis = null;

        try {
            //2. Create FileInputStream object
            fis = new FileInputStream("E:\\file\\code\\java\\day01\\src\\Test\\test.txt");
            //3. Read the file with the read() method of FileInputStream object
            /*
            System.out.println("\n Number of bytes that can be read: "+ fis.available());
            int data;Integer representation of each byte read
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }
            System.out.println("\n Number of bytes that can be read: "+ fis.available());
            */
            //3. Read the file with the read(byte []) method of FileInputStream object
            byte[] b = new byte[1024];
            int data;//Bytes read
            while ((data = fis.read(b)) != -1) {
                //Bytes are read into byte array b, and cyclic output is required
                for (int i = 0; i < data; i++) {
                    System.out.print((char) b[i]);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. Close the input stream
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

OuputStream and FileOuputStream

Common methods of OutputStream and FileOutputStream
  • Common methods of OutputStream

    void write(int c) writes bytes to the output stream one by one

    void write(byte[] buf) writes a byte array to the output stream

    void write(byte[] b,int off,int len): write a byte array to the output stream. Off means to start writing out from the off position of the byte array, and Len means to write out bytes of len length

    void close(): close the output stream

    void flush(): force the data in the buffer to be written to the output stream

    OutputStream is an abstract base class. To create an object, its subclass FileOutputStream is required.

  • Common construction methods of subclass FileOutputStream

    FileOutputStream(File file)

    FileOutputStream(String pathname)

    FileOutputStream(String pathname,bool append)

The first two construction methods will overwrite the original contents of the file when writing data to the file
When creating the FileOutputStream example, if the corresponding file does not exist, an empty file is automatically created

Example

package Test;
//1. Introduction of resources

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

//Write to file with byte output stream
public class FileOutputStreamDemoTest {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            //2. Create byte output stream object (FileOutputStream)
            fos = new FileOutputStream("E:\\file\\code\\java\\day01\\src\\Test\\test.txt");
            //fos = new FileOutputStream("E:\file\code\java\day01\src\Test\test.txt",true); It means that the file will not be overwritten, but appended
            //3. Call the write() method of the byte output stream object (FileOutputStream) to write the file
            String info = "hello first file";
            //Break the written string into a byte array
            byte[] infos = info.getBytes();
            fos.write(infos, 0, infos.length);
            System.out.println("test The file has been updated!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. Turn off the output stream
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Copy files

E: \ file \ mysoft \ deveco studio \ deveeco studio 2.1.0.501 \ note TXT text file to e: \ file \ code \ Java \ day01 \ SRC \ test \ note Txt, in fact, copying is to read the text file first, read the text file, then create a text file at the specified location, and then write the text file

package Test;

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

//With the comprehensive use of byte input and output streams, file copying (reading and writing) is realized
//E:\file\mysoft\deveco-studio\DevEco Studio 2.1.0.501\NOTICE.txt-->E:\file\code\java\day01\src\Test\NOTICE.txt
public class InAndOutStreamDemoTest {
    public static void main(String[] args) {
        FileInputStream fis = null;//Input stream read
        FileOutputStream fos = null;//Output stream write
        try {
            fis = new FileInputStream("E:\\file\\mysoft\\deveco-studio\\DevEco Studio 2.1.0.501\\NOTICE.txt");
            fos = new FileOutputStream("E:\\file\\code\\java\\day01\\src\\Test\\NOTICE.txt");
            byte[] words = new byte[1024];
            int len = -1;
            //The contents of the file are read out and stored in the byte array words
            while ((len = fis.read(words)) != -1) {
                //Write out the byte array words to the output stream fos
                fos.write(words, 0, len);
            }
            System.out.println("File copy complete");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Keywords: Java

Added by s_ainley87 on Tue, 18 Jan 2022 04:32:23 +0200