Java’s file operations and IO

Time:2023-11-22

catalogs

I. Recognizing documents

1.1 What is a document?

1.2 Organization of documentation

1.3 File path

1.4 Classification of documents

II. File operations

2.1 File Overview

III. File content manipulation – IO

3.1 JavaIO Awareness

3.2Reader and Writer

Reader class

Writer class

3.2FileInputStream and FileOutputStream

The FileInputStream class

The FileOutputStream class

IV. Summary


🎁Personal homepagetq02’s Blog_Blog – C language, Java, Java data structure field blogger
This article was originally written by tq02 and first appeared on
This chapter explains the content:Documentation and IO explained

Java's file operations and IO

Multi-threaded learning column:Multi-threaded Learning Column

Other study columns:C language         JavaSE       MySQL Basics 

       

Before learning about file manipulation, we need to understand the basic information about files in order to know how to manipulate them and use them.

I. Recognizing documents

1.1 What is a document?

Q: Files, are they pictures, documents, videos, zip archives, or that kind of folder?

A: In a sense, it’s all documents.

File: holds the data content, as well as some meta-informationThe data, e.g., file name, file type and file size, etc.

If you own a computer, you will often deal with files, for example: ppt, word, etc.. And for computers, these files are all different, the main difference is that the suffix is different. Files are generally stored in the hard disk.

1.2 Organization of documentation

There are many files on top of the computer, so we have to manage and organize them. But how are they organized? Currently, they are organized through a hierarchical structure, similar to the tree structure we learned in Data Structures, which is the concept of a folder or directory on a computer.

Java's file operations and IO

1.3 File path

There are 2 types of file paths, oneabsolute pathkind ofrelative path

Absolute path:Refers to the path where the file actually exists on the hard disk. It starts at the root directory and continues to the directory where the target file is located, including all parent directories.


For example, if the absolute path of the 1.txt file is “C:\Users\15063\Desktop\1.txt”, then the file is in the Desktop folder in the Users folder in the 15063 file under the C drive.

Relative Path:Path relative to the directory where the current file is located. It describes the location from the current directory to the target file. The relative path can be short, simply indicating the relative location between the current directory and the target file.


Example:1.txtThe file is in C:\Users\15063\1.txt,2.txtIn C:\Users\15064\Desktop\2.txt

So for the 2.txt file, the upper directory is the 15064 directory, and the upper directory is the Users directory, and the 15063 directory is also in a folder under the Users directory, and in that folder there is the 1.txt file.

. /:Current directory . /:upper directory /lower directory

Bonus: On windows, there is no difference between / and \, they both work.

Example: 1.txt file location: C/Users/15063/Desktop/1.txt

In linux, however, you must use /

1.4 Classification of documents

Files are generally categorized into 2 types, depending on the data they hold.Text and binary files

Text files Binary files

Stores characters (utf8 character set) Stores binary data

Q: How can I tell if a file is character or binary?

A: Use Notepad to open it, if you can read it, it is a text file, if you can’t read it, it is a binary file.

II. File operations

        file operationis a term used in theThe process of reading, writing, modifying, and performing various operations on files in a computer. File operations can include creating and deleting files, opening and closing files, reading and writing file contents, etc.

2.1 File Overview

This chapter uses the Java approach to file manipulation. A file (including a directory) is abstractly described in Java by the java.io.File class. Note that the existence of a File object does not mean that the file actually exists. file can only operate on files, not their contents.

Constructor methods of the File classclarification
File(File parent,String Child)Create a new instance of File based on the parent directory and child file paths
File(String pathname)Create a new instance of File based on the path to the file, path mode: absolute and relative
File(String parent,String Child)

Create a new instance of File, based on the parent directory and child file paths.

The parent directory is represented by a path

Personally, I think the File is for the compiler to find the corresponding directory and not care if the file will be there. We generally use the middle constructor:File(String pathname)If you want to check if a file exists, get the path or create a file, etc., you need to use theFiled approach

Methods of the File classReturn Typeclarification
getParent()       StringReturns the file path of the parent directory of the File object
getName()Returns the pure file name of the Fle object
getPath()Returns the file path of the File object
getAbsolutePath()Returns the absolute path of the File object
exists()booleanDetermine whether the file described by the File object really exists
isDirectoryDetermines whether the file represented by the File object is a directory.
isFile()Determine whether the file represented by the File object is an ordinary file.
createNewFile()Automatically create an empty file according to the File object. Returns true after successful creation.
delet()Delete the file according to the File object. Returns true if the deletion is successful
mkdirs()Creates the directory represented by the File object and, if necessary, an intermediate directory.
renameTo(File dest)The file renaming can also be considered as our usual cut and paste operation.
deleteOnExit()voidAccording to the File object, mark this file and the JVM will delete it at the end of the run.
list()String[ ]Returns the names of all files in the directory represented by the Fle object.
listFiles()File[ ]Returns all files in the directory represented by the File object, expressed as a File object.

Using what we have learned, we can now create, query, etc. documents.

Start by creating a word document:File.txt :

Java's file operations and IO

Use other methods:

Java's file operations and IO

These are all the knowledge points of the File class, but have you found a problem? It seems that you can only create a file, query the location of the file, delete the file, but can not operate on the file!!!!Manipulating the contents of a file also has its corresponding class


III. File content manipulation – IO

3.1 JavaIO Awareness

You can’t manipulate the contents of a file without streams, and the class to use is theFile stream (.stream).

File streams are similar to water streamsFor example, there is a 1000ml bucket, which can be divided into 10 pickups (100ml each), or 5 pickups (200ml each) and so on. When operating the file, it is the same, can be divided into many times to read.


Java IO can be divided into input streams and output streams, which correspond to reading and writing data, respectively. Among them, input streams include InputStream and Reader, and output streams include OutputStream and Writer.

                Classes on manipulating byte streams are: InputStream、OutputStream —- binary file

               Classes for manipulating character streams: Reader, Writer—– text file

Different programming languages have different api’s for file manipulation, but they have the same core steps:

  1. Open file
  2. Close file
  3. read file
  4. write a file

3.2Reader and Writer

JavaReader and Writeris used for character stream input and outputAbstract Classes (that can’t be created directly). They are designed to work with character data, not byte data.Reader and Writer provide a set of methods to read and write character data that can be used to read and write text files and other character streams.

Reader class

Created:Reader object name = new FileReader( file path or File object);

Note: An exception will be thrown, and there may be files that cannot be found, so you need to throw an exception or use try{}catch{}

Code Example:

//Constructor method passes file path
Reader read=new FileReader("D:0 Safe Browser");;

//Constructor method passes File object
File t1=new File("D:0 Secure Browser");
FileReader raeder=new FileReader(t1);

File operations open files and also need to close them.

Close the file:ObjectName.close();

Note: Exceptions are also thrown, and the exception IOException needs to be thrown as well, while theCreating Generated Exceptionsis a subclass of IOException, so just throw the IOException exception immediately.

Consequences of not executing the close() method:

  1. Resulting in leakage of file resources.
  2. The file description table of the PCB of the occupying process will be full, and no new files can be opened subsequently.

For the close() method, we may have a special case that causes the code to not execute to close().

public int add(){
     FileReader raeder=new FileReader(./src/ fil.txt);
     return 10; //The method was called with the file open, but before it was closed, it was terminated with return.
     raeder.close();
}

And for the above case, there is a special usage that makes the code call the close() method automatically

try(Reader object name = new FileReader( file path or File object)){

//Methods to be implemented

}                   

Note: The close() method is automatically called after the try code is executed.This method also applies to other content manipulation classes

Methods of the Reader classaccount for

read()

Retrieve Characters
skip(long n)Number of characters skipped n
ready()Are you ready to read

Code Example:

//Textual contents: 1 2 3 4 5 6 7 8
  try(FileReader t1=new FileReader("./src/ fil.txt "))
   {
        System.out.println( t1.read()); //read the character set number corresponding to 1
        System.out.println( t1.read()); //read the character set number corresponding to 2
        t1.skip(2); //skip 2 characters
        System.out.println(t1.read()); //read the character set number corresponding to 5
     }

Writer class

Created:Writer object name = new FileWriter( path to file or File object );

Note: An exception will be thrown, so you need to throw it or use try{}catch{}.

Code Example:

//Constructor method passes file path
Writer kk=new FileWriter("kk.txt");

//Constructor method passes File object
 File t1=new File("kk.txt");
 FileWriter kk=new FileWriter(t1);
  • FileWriter constructor:
FileWriter(File file)
// use an open file descriptor as a constructor parameter, data will be output to the node corresponding to that file descriptor

FileWriter(File file,FileDescriptor fd)
//append whether to write as append, if this fd is false, the file will be overwritten, append is synonymous with the following
  • Writer method
Writer methodanalysis
append(char c)Appends the specified character c to this.
append(CharSequence csq)directoryCharacter sequence csq write to a file

append(CharSequence csq,int start,int end)

Writes a subsequence of the specified character sequence to a file
write(char[] cbuf)This method writes an array of characters.
 write(char[] cbuf, int off, int len)Write a portion of a character array
 write(int c)Individual characters written (the number c corresponds to theCharacters in Unicode Position
 write(String str)Write a string.
 flush()This method refreshes the stream.
 close()cloture

Code Example:

public static void main(String[] args) throws IOException {
        CharSequence csq = "Hello World!";
        //writer and append write as append, not overwrite
       try(Writer kk=new FileWriter("kk.txt",true))
       {
           //write method
            char[] array={'a','b','c','d'};
            kk.write(array); //pass the array to the file
            kk.write(100);// The corresponding Unicode table is d;
            kk.write("\nHello World! \n\n"); //pass the string to the file
            kk.flush(); //flush to save the data;

           //append method
           kk.append('c');
           kk.append(csq,0,5); //pass the sub-sequence of 0 to 5 of the character sequence of csq to the file
           kk.append(csq); //pass the sequence of characters from csq to the file
           kk.flush(); //flush to save the data;

           // No need to use close();.
       }

Note:Although the append method cannot pass a string, it can be used to pass a string by means of theCharSequence, passing a sequence of characters to reach the same result.

  • Difference between append and write:
  1. The append method is an overloaded method in the Writer class. There are several append methods in the Writer class that are used to add characters, strings, character arrays, and so on, to the output stream. write has only one method that accepts an array of characters or a string argument.

  2. The return value of the append method is an instance of the Writer object that calls the method, and you can chain calls to multiple append methods to achieve continuous output. The write method has no return value.

  3. The append method can add any type of data to the output stream, including null, while the write method cannot output null, or a NullPointerException is thrown.

  4. The append method can append characters to the output stream, while the write method can only output all the characters at once and cannot append them.

In summary, the append method is more flexible and can be used to add different types of data to the output stream, while the write method is simpler and can only output strings or arrays of characters and cannot append data.


3.2FileInputStream and FileOutputStream

In the InputStream class and OutputStream class, we mainly explain their subclasses FileInputStream class and FileOutputStream class.

Notes:FileInputStream and FileOutputStream operate on files as bytes.

The FileInputStream class

The FileInputStream class is used to extract a file from theretrieveByte Stream. ItInherited from InputStream class, and provides a number of methods to read data from a file. You can use it to open a file and read data from the file byte by byte. Not only can you read text content, but you can even read image files. Note: A byte is 8 bits

Construction Methods:

//Constructing file output streams with File
File t1=new File("kk.txt");
FileInputStream t2=new FileInputStream(t1) 

// Construct file input streams using file paths
InputStream t2=new FileInputStream(String name)

Notes:Text files can also be opened using byte streams. However, since it is reading every byte, it may not represent the full character.

FileInputStream method:

methodologiesanalysis
read(byte[] b,int off,int len)Read len bytes at a time, starting from the array off subscript, fill len bytes, return the number of bytes read
read(byte[] b)Reads up to b.length bytes of data into the byte array b at a time, returning the number of bytes read.
read()Reads a character, this method blocks if no input is available. Returns the byte data
skip()

Skip and discard from the input streamnbytes of data.

available()Returns an estimate of the number of bytes remaining in the input stream.

Returns 0 if the file location is out of EOF

close()

Closes this file input stream and releases any system resources associated with the stream. Note: This method can be omitted by using try.

Code Example:

public static void main(String[] args) throws IOException {
// Use try, you can not use close() method
        try(InputStream inputStream=new FileInputStream("kk.txt")) {
//Query how many bytes are left in the kk file.
    System.out.println(inputStream.available());   
//Query what is the current byte?        
     System.out.println(inputStream.read());
// pass the contents of the file into the array aa
     byte[] aa=new byte[10];
     int a=inputStream.read(aa,3,4); //store 3 bytes of the input stream by subscripting the array to start at 3.
                                      // Returns, number of stores
      int b=inputStream.read(aa); //returns an array to store the number of input streams         
    }
}

qHow can I convert the bytes I read into the original content? For example, the text is text, etc., but it is read out as bytes and the original content is not known.

a: 2 methods

  1. Byte to string conversion is accomplished with the help of some additional tool classes
  2. Use the String class directly, using the constructor method.

Method I:

public static void main(String[] args) throws IOException {
                                        //Documentation reads I love you, Java
  try(InputStream inputStream=new FileInputStream("kk.txt")) { 
     byte[] aa=new byte[1024];
     int a=inputStream.read(aa); input the text into the array byte.
      
      String t1=new String(aa,0,a,"utf8");
    System.out.println(aa); //output: I love you, Java        
    }
}

Method 2: Tool class: Scanner, which converts the currently read byte data. The data can be standard input or other sources. Note: Binary files cannot be read.

try(InputStream inputStream=new FileInputStream("kk.txt")) {
    // Read data from the keyboard
      Scanner scan=new Scanner(System.in);

    //This is the time to read data from the file.
      Scanner sc=new Scanner(inputStream);
         String s=sc.next();
         System.out.println(s);
}

Extra: Adjusting the idea’s character set: File–>Settings

Java's file operations and IO

The FileOutputStream class

The FileOutputStream class is used to write a stream of bytes to a file. It inherits from the OutputStream class and provides methods to write data to a file. You can use it to create a new file or overwrite an existing file and write byte data to the file. For example, you can use FileOutputStream to write text data to a new file or write image data to an image file.

Construction Methods:

//Constructing a file input stream using File
File t1=new File("kk.txt");
FileOutputStream t2=new FileOutputStream(t1) 

// Construct file input streams using file paths
OutputStream t2=new FileOutputStream(String name)

OutputStream methods:

methodologiesanalysis
close()Closes this output stream and releases any system resources associated with this stream.
flush()Flushes this output stream and forces any buffered output bytes to be written.
write(byte[] b)Inputting byte arrays into a file
write(byte[ ] b,int off,int len)Input len bytes into the file, starting at the position labeled off.

write(int b)

Enter the specified bytes into the document

As with the InputStream methods, which can be paired with the Scanner() method, theOutputStream can be used with PrintWriter.

import java.io.*;

public class PrintWriterExample {
    public static void main(String[] args) {
        try {
            OutputStream outputStream = new FileOutputStream("kk.txt");
            PrintWriter printWriter = new PrintWriter(outputStream);

            printWriter.println("Hello, World!");
            printWriter.println("This is an example.");

            printWriter.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the above example, we created a file named kk.txt and made it the target of the output stream. Then, we created the PrintWriter object and passed the outputStream as an argument to it. Finally, we use printWriter’s println method to write the text content and close printWriter and outputStream at the end.In this way, the text will be written to the output.txt file. You can modify the target of the output and the content to be written according to your needs.


IV. Summary

  1. Byte operations.InputStream、OutputStream    character operation:Reader、Writer
  2. Using the try method prevents you from forgetting the close() method.
  3. Scanner tool class, you can read the keyboard input data, you can also receive text data, but can not read the binary file
  4. PrintWriter with OutputStream, can simplify the code effect, provides a printf, println and other methods to write directly to the file
  5. Output stream objects (either byte or character streams) will empty the contents of the file after opening it. However, you can use the append method, which will not empty the contents at this point.

Recommended Today

Resolved the Java. SQL. SQLNonTransientConnectionException: Could not create connection to the database server abnormal correctly solved

Resolved Java. SQL. SQLNonTransientConnectionException: Could not create connection to the database server abnormal correct solution, kiss measuring effective!!!!!! Article Catalog report an error problemSolutionscureexchanges report an error problem java.sql.SQLNonTransientConnectionException:Could not create connection to database server Solutions The error “java.sql.SQLNonTransientConnectionException:Could not create connection to database server” is usually caused by an inability to connect to the […]