File operation:

This is the 31st day of my participation in the August Text Challenge.More challenges in August

FIle manipulation is just a FIle class; We learned File manipulation by studying methods in the File class;

File base operation:

Part 1: Learn the basic operation of the document (check the manual first)

Constructor Description
File(File parent, String child) Gives the name of the parent path and child file of the query to operate on
File(String pathname) Given a full path to the file to manipulate
Modifier and Type Method Description
boolean public boolean createNewFile() throws IOException Create a file
boolean delete() Delete the file
boolean exists() Determines whether the given path exists

Here’s an example:

import java.io.File;
import java.io.IOException;

public class FIleDelCre {
    public static void main(String[] args) throws IOException {
        File file = new File("e:\\IOFileSource\\xbhog.txt");
        if(file.exists()){
            file.delete();
        }else{ System.out.println(file.createNewFile()); }}}Copy the code

CreateNewFile: True if the specified file does not exist and has been successfully created. False if the specified file already exists

Knowledge point (type on blackboard) :

Path delimiters: Solve the problem of path symbols on different operating systems (Windows -> “\”; Linux – > “/”);

File file = new File("e:"+File.separator +"IOFileSource"+File.separator+"xbhog.txt");
Copy the code

Note:

/**
     * The system-dependent default name-separator character, represented as a
     * string for convenience.  This string contains a single character, namely
     * {@link #separatorChar}.
*/
public static final String separator = "" + separatorChar;
Copy the code

To operate on the parent path:

import java.io.File;
import java.io.IOException;

public class FIleDelCre {
    public static void main(String[] args) throws IOException {
        File file = new File("e:"+File.separator +"IOFileSource"+File.separator+"test"+File.separator+"demo"+File.separator+"xbhog.txt");
        if(! file.getParentFile().exists()){// If the file's parent directory does not exist
            /* file.getParentFile().mkdirs(); File.getparentfile ().mkdir(); Create a parent directory */
        }
        if(file.exists()){
            file.delete();
        }else{ System.out.println(file.createNewFile()); }}}Copy the code

Note: mkdirs and mkdir difference, it is best to enter the source view

File list display:

Flow chart:

import java.io.File;
public class FilePwd {
    public static void main(String[] args) {
        File file = new File("D:" + File.separator);
		listDir(file);
    }
    public static void listDir(File file){
        if(file.isDirectory()){
            File[] Dirs = file.listFiles();
            while(Dirs ! =null) {for (int i = 0; i < Dirs.length; i++) {
                    listDir(Dirs[i]);  // recursive call} } } System.out.println(file); }}Copy the code

File batch rename:

Situation:

In the process of data collection, the suffix of all files in xbhog-log folder was.java due to an error. In order to correct this error, it is required to replace the suffix of all files in this directory with.txt. Meanwhile, the rename operation of files in multi-level directory should also be considered.

import java.io.File;
public class FIleChangeName {
    public static void main(String[] args) {
        File file = new File("D:" + File.separator + "xbhog-log");
        renameDir(file);

    }
    public static void renameDir(File file){
        if(file.isDirectory()){
            File[] dirs = file.listFiles(); 
            for (int i = 0; i < dirs.length; i++) {
                renameDir(dirs[i]);  // recursive call}}else {
            if (file.isFile()){ // The experience is a file
                String fileName = null;  // File name
                if(file.getName().endsWith(".java")) {// Check whether the.java end is used
                    fileName = file.getName().substring(0,file.getName().lastIndexOf(".")) +".txt";
                    File newfile = new File(file.getParentFile(), fileName);  // The new file name
                    file.renameTo(newfile);  / / renamed
                }
            }
        }
    }
}
Copy the code

Byte stream and character stream:

Byte streams: outputStream and inputStream

Character streams: Writer and Reader

Basic steps for resource operations :(file as an example)- follow these steps exactly

  1. If the resource to operate on is a File, you first need to find a path to the File to operate on through the File class object
  2. Instantiate an object for byte stream or character stream by subclass of byte stream or character stream (uptransition)
  3. Perform read and write operations
  4. Close the resource

OutputStream Indicates a byte input stream

Common class methods:

Modifier and Type Method Description
void close() Close this output stream and release any system resources associated with this stream.
void flush() Flushes this output stream and forces any buffered output bytes to be written.
void write(byte[] b) Output a single byte of data
void write(byte[] b, int off, int len) Output partial bytes of data
abstract void write(int b) Output a set of bytes of data

Operations on files require a subclass of FileOutputStream to instantiate the object.

Its common construction method is:

Constructor Description
FileOutputStream(File file) Creates a file output stream to write to the file represented by the specified file object.
FileOutputStream(File file, boolean append) Creates a file output stream to write to the file represented by the specified file object. If the second argument is true, the bytes are written to the end of the file instead of the beginning

Example:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class FIleOutputStearm {
    public static void main(String[] args) throws IOException {
        File file = new File("xbhog.txt");
        if(! file.exists()){ file.createNewFile(); } OutputStream outputStearm =new FileOutputStream(file);
        String str = "Welcome to xbHOG's blog."; outputStearm.write(str.getBytes(StandardCharsets.UTF_8)); outputStearm.close(); }}Copy the code

Appending file contents:

    OutputStream stream = new FileOutputStream(file, true);
    String addStr = "----- this is an add-on ------";
    stream.write(addStr.getBytes());
    stream.close();
Copy the code

InputStream byte InputStream:

Common methods for this class:

Modifier and Type Method Description
void close() Turn off the output stream
abstract int read() Reads a single byte of data, and returns -1 if it has been read to the end
int read(byte[] b) Reading a set of bytes returns the number of bytes read, or -1 if no data has been read at all
int read(byte[] b, int off, int len) Read a set of bytes (only part of the array)
byte[] readAllBytes() Read all bytes of data from the input stream
long transferTo(OutputStream out) The input stream is stored in the output stream, which was added after JDK 1.9

Operations on files require a subclass of FileInputStream to instantiate the object.

Common uses for reading files:

  1. Create file input stream —InputStream input = new FileInputStream(file)
  2. Set the read cache for data —-new byte[1024]
  3. Read data, read data into the cache and put back the number of bytes read —-int len = input.read(data)
  4. Bytes are converted to a stream of characters —-new String(data,0,len)
  5. Close the resource

Example of reading file contents:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileInputStreamTest {
    public static void main(String[] args) throws IOException {
        File file = new File("xbhog.txt"); // Output file path
        if (file.exists()) {    // File exists
            InputStream input = new FileInputStream(file);// File input stream
            byte data[] = new byte[1024]; // Data read buffer
            // Read the data into the buffer, and return the number of bytes read
            int len = input.read(data);
            System.out.println("【" + new String(data, 0, len) + "】");// Bytes are converted to strings
            input.close();    // Close the input stream}}}Copy the code

Read the entire contents of the file:

byte[] bytes = input.readAllBytes();
System.out.println(new String(bytes));
Copy the code

Writer character stream:

To simplify the operation of output, Writer and Reader character streams are provided.

Common methods for this class:

Modifier and Type Method Description
Writer append(char c) Writes the specified character to.
Writer append(CharSequence csq) Appends the specified character sequence to this writer.
Writer append(CharSequence csq, int start, int end) Appends a subsequence of the specified character sequence to this writer
abstract void close() Close the resource
abstract void flush() Refreshing a resource flow
void write(char[] cbuf) Writes to an array of characters
abstract void write(char[] cbuf, int off, int len) Writes part of an array of characters
void write(int c) Write a character
void write(String str) Write a string
void write(String str, int off, int len) Writes part of a string

When writing a file stream, you need to introduce the FileWriter subclass of Writer.

Class project structure:

  • java.lang.Object
    • java.io.Writer
      • java.io.OutputStreamWriter
        • java.io.FileWriter

FileWriter:

Constructor Description
FileWriter(File file) Given a File object, construct a FileWriter object.
FileWriter(String fileName, boolean append) Constructs a FileWriter object with a given filename that has a Boolean value indicating whether to append the data to be written.

Example:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class FileWriterDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("FileWriter.txt"); // Output file path
        if(! file.exists()){ file.createNewFile(); } Writer out =new FileWriter(file) ; // Instantiate the Writer class object
        out.write("Welcome to XBHOG");	// Outputs a string
        out.write("\n");
        out.append("Test\n");
        out.append("www.cblog.cn/xbhog");// Append the output
        out.close();// Close the output stream}}Copy the code

Reader character input stream:

Common methods of this class:

Modifier and Type Method Description
abstract void close() Close the resource
int read() Reading a single character
int read(char[] cbuf) Puts a character into an array
long skip(long n) Skip characters (several)
boolean ready() Determines whether the stream is ready to be read

Example test:

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class FileReaderDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("FileWriter.txt");// Output file path
        if (file.exists()) {// File exists
            Reader in = new FileReader(file);  // instantiate the input stream
            char data[] = new char[1024];  / / the buffer
            // "Welcome is gone"
            in.skip(2);// spans 2 characters
            int len = in.read(data); // Read data
            System.out.println(new String(data, 0, len));
            in.close();// Close the input stream}}}Copy the code

Transformation flows:

Transformation flows OutputStreamWriter InputStreamReader
Inheritance structure public class OutputStreamWriterextends Writer {} public class InputStreamReaderextends Reader
A constructor public OutputStreamWriter(OutputStream out) public InputStreamReader(InputStream in)

To implement the conversion operation of the two:

Converts a byte input stream into a character input stream

import java.io.*;
public class ConversionOperations {
    public static void main(String[] args) throws IOException {
        File file = new File("FileWriter1.txt"); 	// Output file path
        OutputStream output = new FileOutputStream(file) ;/ / byte streams
        Writer out = new OutputStreamWriter(output) ; 	// byte flow character stream
        out.write("Test the conversion between the two."); // Character stream output
        out.close();	// Close the output stream
        output.close(); 	// Close the output stream}}Copy the code

The end:

If you see this or happen to help you, please click 👍 or ⭐ thank you;

There are mistakes, welcome to point out in the comments, the author will see the modification.