Location>code7788 >text

Java File I/O Streams Explained

Popularity:426 ℃/2024-08-04 11:33:46

file

File operation is an important part of Java development , which allows developers to read, write , create, delete and modify files and other operations , file operations mainly through thepackage, which is implemented by classes in theFileclass is the core class for file manipulation

Common methods of the File class

Create a file or directory

  • File Creation

    utilizationcreateNewFile();A new empty file can be createdIf the file already exists, it is not created and is placed back in thefalse, which creates the file anyway and returnstrue

    public class Test1 {
        public static void main(String[] args) {
          
          //create a file object with path "D:\\\java_develop\\\")
          //This step does not create a file yet.
            try { //The try-catch here is mainly used to catch file path not found exceptions.
                boolean isFileCreate=(); //Use createNewFileCreate to create a new file.
                // Use the createNewFile() method to try to create the file again for the specified file
                // and assigns its putback value to isFileCreate
                if (isFileCreate)
                { // Determine if the file has been created based on the value of isFileCreate.
                    ("File created successfully");
                }
                else
                {
                    ("File already exists"); } else {
                }
            } catch (Exception e) {
                 (); } catch (Exception e) {
            }
        }
    }
    

    This code, when executed, will reappear on the D drive under the namejava_developfile to create adocuments

  • Catalog Creation

    Creating a directory is actually under the file systemGenerate a new directory (also known as a folder)Directories can be used to store files or other directories to categorize and group files.

    • mkdir() :for the creation ofFileobject represents a single-level directory, if the created directory does not have a husband-level directory, these husband directories will not be created and return thefalse , e.g. you want to add the"D:\\java_develop\\demo\\folder” Path to create a directory, if the dome directory does not exist, it will fail.
     File dir = new File("D:\\java_develop\\demo");
        //establishFileobject passes in its path
        
            try {
                boolean isCreateDir=();
                //utilizationmkdir()方法establish目录
                if (isCreateDir) //pass (a bill or inspection etc)mkdir()return value,判断目录是否establish
                {
                    ("dir creates successfully");
                }
                else
                {
                    ("fail to create dir");
                }
            } catch (Exception e) {
               ();
            }
    

    The above code, when executed, will create a file on the D drivejava_developfolder to create ademofile (paper)

    • mkdirs(): Create a multilevel directory atmkdir()In contrast.mkdirs() In the parent directory does not exist, will give priority to create the parent directory, and then create its subdirectories, even if the next directory level does not exist, you can create the entire directory path, so as to realize the creation of multi-level directories, the creation of a successful return to thetrue
    File dir = new File("D:\\java_develop\\demo\\inside");
    //Creates a path with theFileboyfriend
            try {
                boolean isDirCreate=();//utilizationmkdirs()Creating Multi-Level Catalogs
                if (isDirCreate)
                {
                    ("Dir creates successfully");
                }
                else
                {
                    ("Failed to create Dir");
                }
            } catch (Exception e) {
                ();
            }
    

    After execution, it will be placed on the D drivejava_developCreatedemofolder, in thedemoThe folder createsinsidefile (paper)

Get document information

  • exists(): Determine if the file or directory exists, return if it exists.true, and vice versa returnfalse
  • getName():ReturnFileName string of the object's file or directory
  • getParent() : Get the parent path of the file or directory, if the file or directory does not have a parent path, then return the parent path of the file or directory.null
  • isFile():: Determine that thisFileWhether the object is a file (as opposed to a directory)
  • isDirectory() : Determine if this File object is a directory (and not a file).
  • listFiles() :Back to oneFilearrays, theseFileobject representation thusFilefiles and directories in the directory represented by the object. If thisFileobject does not represent a directory, then this method returnsnull , can be used to get all the folders/names in a directory
  • length(): Get file size value
    File file = new File("D:\\java_develop");
        File fileArray[]=();
        for (File f : fileArray) {
            (());
        }
    }

Delete a file or directory

  • delete() : Delete a file or empty directory. If the deletion is of a directory, the directory must be empty, otherwise the deletion fails and returns thefalse
     File file = new File("D:\\java_develop\\");
       if (())
       {
           ();
       }
    }

Rename a file

renameTo(File dest): Rename the document to this nameFileThe pathname represented by the object. If the target file already exists, the file will be deleted and the rename operation will then attempt to perform the

 File file = new File("D:\\\java_develop\\\\");
        File file1 = new File("D:\\\java_develop\\\");
        if (())//check if file object exists
        {// If it exists, rename it to the path of file1
            (file1); if ())//check if file object exists {// then rename it to file1 path.
        }
    }

After the above code is run, the originalwill be changed to

IO flow

JavaIO(input/output)is the basis for the realization of input and output , you can easily realize the data input and output operations , Java to the different input/output sources abstracted into a "stream (stream)", which passed the one by one/block of data read and write way, theA stream is a sequential collection of bytes with a start and end point, and is a general term or abstraction for data transmission. That is, the transfer of data between two devices becomes a stream thatThe essence of streaming is data transfer

Categories of IO streams

  • IO streams are divided intoCharacter Streams and Byte Streams, which is divided into input and output streams.If it is an audio file, picture, song, it is better to use byte stream, if it is related to Chinese, it is better to use character stream. Byte streams can be used for any type of object, including binary objects, while character streams can only handle characters or strings. Byte streams provide the ability to handle any type of IO operation, but it can't handle Unicode characters directly, while character streams can.

The following are the basic categorization categories for IO streams.

stream of characters

Character stream is a data stream that reads and writes characters (char) as the lowest unit. Mainly used for processing text data, such as characters, strings and so on. Character streams are read and written through theReadercap (a poem)Writer class and its subclasses implement the

Reader

  • is the superclass of all character input streams, it defines some basic methods such asread(),ready(),skip(), andclose()
  • int read(): The returned data type isinttype, when reading a single character, the return is itsUnicodevalue, read to the end of the stream, return -1
  • int read( char []ch): Write characters to the array, and return the number of characters read, read to the end of the stream, return -1
  • void close():: Close the stream and release the resources associated with it.

Writer

  • is the superclass of all character output streams
  • void write(int c):Write single character
  • void write(char []ch): Write to character array
  • void write(char[] cbuf) maybevoid write(char[] cbuf, int off, int len): Write to a character array or part of a character array. Again, these methods have no return value
  • void flush(): Refreshes the writer's buffer, forcing all buffered characters to be written.
  • void close(): Shut down the writer and release all its system-related resources, and do it every time you output.close()operation, because it is possible that the characters in the buffer have not yet been written in, using theclose()Perform a mandatory write out

Buffered

  • BufferedSpecifically, the mechanism creates a buffer in memory to reduce the number of operations in the actual I/O stream.
  • underlying principle: Data is first written or read into a buffer in memory, rather than being subjected to a direct I/O operation. Once the buffer is full or a condition is reached (e.g., an explicit call to theflush()method), the contents of the buffer will be written to or read from the disk in a single pass.
  • Difference between Buffered and File.
File Buffered (BufferedReader as an example)
Definitions and Functions Encapsulates the operational features of the file system, focusing on the storage of files on disk. Provide input/output methods with buffers, focusing on efficient reading/writing of data.
Primary methodology getName(), getPath(), exists(), createNewFile(), delete() and so on. read(), readLine(), mark(), reset(), etc. (BufferedReader specific).
use Used to indicate the pathname of files and directories, to perform operations such as file or directory creation, deletion, and renaming. Used to read text data efficiently, especially large files.
Ways in which data are processed Direct operation of files or directories of the file system does not involve buffering of data. The buffer is 8192 bytes The internal buffer is used to reduce the number of I/O operations and improve the efficiency of data processing. The buffer is 8192 characters
try {
            FileReader reader = new FileReader("D:\\java_develop\\");
            FileWriter writer = new FileWriter("D:\\java_develop\\");
            int ch;
            while((ch=())!=-1)
            {// asreadcome (or go) back-1Explain that reading to the end of the file will jump out of the loop directly.
              (ch);
            }
            ();
            ();
        } catch (IOException e) {
            ();
        }

streams of nibbles

is used to process raw byte data , byte streams are very suitable for processing binary files , such as photos , audio , video or any non-text format of the data . Java in the byte stream of the basic classes areInputStreamcap (a poem)OutputStream

InputStream and OutStream

  • InputStream:: Used to read bytes of data from a data source. The data source can be a file, a network connection, an array of bytes in memory, etc.
  • OutputStream : Used to write bytes of data to the destination, with theInputStreamThe same data source could be a file, a network connection, an array of bytes in memory, etc.

Basic Operation Methods

  • int (): read a single byte or an array of bytes, the return value isinttypology
  • int (byte b[]):Exists the read data in thebyte b[]array
  • void (int b): Write single byte
  • void (byte b[]): Write the data in the byte b[] array to the
  • void (byte[] b, int off, int len): Write the specified portion of the byte array.
  • close(): Closes the stream, freeing up system resources.
  • getBytes():Get byte array
  • nodal flow
    • FileInputStream cap (a poem)FileOutputStream: Used to read and write bytes of data in a file.
    • ByteArrayInputStream cap (a poem)ByteArrayOutputStream: Used to read and write byte arrays in memory.
    • () cap (a poem)(): Used to handle the transfer of byte data over a network connection.
  • filtration flow
    • BufferedInputStream cap (a poem)BufferedOutputStream: Add buffering mechanisms to byte streams to improve read and write efficiency.
    • DataInputStream cap (a poem)DataOutputStream: Provides the ability to read and write basic data types (such asintdouble etc.) of the capacity.
    • ObjectInputStream cap (a poem)ObjectOutputStream: Used for serialization and deserialization of objects, i.e. reading and writing of objects.
try {
            FileInputStream inputStream = new FileInputStream("D:\\java_develop\\");
            FileOutputStream outputStream = new FileOutputStream("D:\\java_develop\\");
            byte[] bytes = new byte[1024]; //Setting the buffer1024B
            int len;
            while ((len=(bytes))!=-1)//Stores the read data into the buffer
            {
                (bytes,0,len);//Writes the data in the buffer to the
            }
            ();
            ();//Stop the flow.
        } catch (IOException e) {
            ();
        }

The above example is from putting theCopy the contents of thecenter