Xi - IO flow

1, File abstract class

Abstract representation of file and directory pathnames.

The File or folder or path represented by the File class does not necessarily exist.

  • This class is mainly used for:
    • Creation and deletion of files
    • Creation and deletion of folders

1. Relative / absolute path

object of reference

(1) Relative path

  • Reference is self = > current directory
  1. . / is the current directory

  2. .. / is the parent directory

  3. /Is the root directory

  • . / demo = > current directory, relative to the path of java.txt
  • . / demo / home = > enter its subdirectory
  • ... / Java. MD = > parent directory, enter the upper directory and specify the java.md file

(2) Absolute path

The reference object is the starting point (root) of the path = > fixed position
D:\Java\JAVASE.md

(3) Efficiency of relative path and absolute path

  1. Higher absolute path efficiency
  2. Try to use absolute paths in the program

2. Create files / folders

(1) Create file

  1. You need to determine whether the file exists first:
  2. Then create the corresponding file:

Example: create a FileDemo.java in the directory D:\Java

// base path
String path = "D:/Java/";
// Name of the new file
String fileName = "FileDemo.java";
String filePath = path+fileName;
System.out.println(filePath);
// Create an abstract object of File
File file = new File(filePath);
if (!file.exists()){
	// This file does not exist before you go back to create the corresponding file
	boolean newFile = file.createNewFile();
	System.out.println(newFile);
}

(2) Create folder

// create folder
String parent = "D:/Java/";
String child = "IO";

// abstract
File dirFile = new File(parent, child);

// First judge whether it exists
if (!dirFile.exists()) {
	dirFile.mkdir();
} 

// Continue creating child directories
// 2021/09/20
File dirFile2 = new File(dirFile, "2021/09/20");

// Judge first
if (!dirFile2.exists()) {
	dirFile2.mkdirs();
}

3. Delete files / folders

(1) Delete file

// Basic path
String path = "D:/Java/";

// Building File objects
File file = new File(path, "FileDemo.java");

// Call delete
if (file.exists()){
	file.delete();
}

(3) Delete folder

// remove folders
// Delete this method can only delete empty folders
// How to delete a non empty folder?
File test = new File(path, "test");

if (test.exists()){
	test.delete();
} 

File io = new File(path, "IO");
if (io.exists()){
	io.delete();
}

How to delete a non empty folder?

  • You need to delete files or folders under non empty folders, and so on

4. List of presentation documents

Get all the files or folders under the corresponding path

// Basic path
String path = "D:/Java/";

// Build the File object first
File file = new File(path);

// Get a list of all files
String[] list = file.list();
for (String f : list) {
	System.out.println(f);
}

practice

List all the files / folders under a folder, which must reflect the hierarchical relationship

IO
–2021
----08
------11
–file.txt

  • Core idea: recursion = call yourself
public class Practice {
    public static void main(String[] args) {

        String path = "D:/Java/";
        // Separator--
        // Increase each floor--
        String delimiter = "";
        listFiles(delimiter, path);


    }

    /**
     * Presentation documents
     * @param delimiter  Hierarchy
     * @param path
     */
    public static void listFiles(String delimiter, String path){
        // Build the File first
        File file = new File(path);
        // Get file list
        String[] fileList = file.list();
        // Traversal output
        for (String fileName : fileList) {

            System.out.println(delimiter + fileName);
            // If it is a folder, the same operation is performed
            // First build the inner layer file object
            File dirFile = new File(file, fileName);
            if (dirFile.isDirectory()){
                delimiter += "--";
                listFiles(delimiter, dirFile.getPath());
            }
            // reduction
            if (dirFile.isDirectory()){
                delimiter = doDelimiter(delimiter);
            }

        }
    }

    /**
     * Processing level
     * @param delimiter
     * @return
     */
    public static String doDelimiter(String delimiter){
        if ("".equals(delimiter)){
            return "";
        }
        if (delimiter.length() != 0){
            // ------  =>  ----
            // 012345
            return delimiter.substring(0, delimiter.length()-2);
        }
        return "";
    }
}

2, RandomAccessFile

This class is mainly used to read or write file contents

1. Constructor

2. Writing documents

String path = "D:/Java/Hello.txt";
// Building raf objects
RandomAccessFile raf = new RandomAccessFile(path, "rw");

// Write data
String content = "Hello Java!";
raf.write(content.getBytes());

// Close flow
raf.close();

3. Addition of document content

String path = "D:/Java/Demo.txt";

// Building raf objects
RandomAccessFile raf = new RandomAccessFile(path, "rw");

// Get the length of the file first
long length = raf.length();

// Sets the position of the pointer offset
raf.seek(length);

// Write data
raf.write("\nI LOVE bdls".getBytes());
raf.close();

4. Reading documents

String path = "D:/Java/Demo.txt";
// Building raf objects
RandomAccessFile raf = new RandomAccessFile(path, "rw");
// Read out the data
// Get the length of the file content first
int length = (int) raf.length();
byte[] bytes = new byte[length];

raf.read(bytes);
System.out.println(new String(bytes));

raf.close();

Example of copying files

/**
* Copy a new file named "copy_; original file name", and the content of the file is a copy of the original file.
*/
public class Demo04 {
	public static void main(String[] args) throws IOException {
	// route
	String basePath = "D:/Java/";
	String oldFileName = "Demo.txt";
	
	// File abstraction
	File oldFile = new File(basePath, oldFileName);
	if (oldFile.exists()) {
		// Prepare a new name
		String newFileName = "Copy_"+oldFileName;
		
		// Create newFileName
		File newFile = new File(basePath, newFileName);
		newFile.createNewFile();
		
		// Prepare to copy the contents of the file
		// oldFile => read
		// newFile => write
		// Prepare two randomAccessFile objects
		RandomAccessFile oldRaf = new RandomAccessFile(oldFile, "rw");
		RandomAccessFile newRaf = new RandomAccessFile(newFile, "rw");
		
		// Read out the old data
		byte[] bytes = new byte[(int) oldRaf.length()];
		oldRaf.read(bytes);
		
		// Write data to a new file
		newRaf.write(bytes);
		
		oldRaf.close();
		newRaf.close();
		}
	}
}

Practice copying files
Copy a picture anywhere on the computer: mm. JPG = > copy_ mm.jpg

Intercept mp3 music clips

Intercept the climax of a song! About 10 seconds
There is a rule in this place: the relationship between bit rate, time and location
position = bit rate * time (s) * 1024 / 8
Daoxiang. MP3 = > 23S ~ 33S

// route
String path = "D:/Java/dx.mp3";
// Bit rate
int bit = 128;
// Calculate the start position = > 23S
long startPos = bit*23*1024/8;
// Calculation end position = > 33S
long endPos = bit*33*1024/8;
// Part to be intercepted: endpos startpos
System.out.println(endPos-startPos);

// Prepare the raf object first
RandomAccessFile raf = new RandomAccessFile(path, "rw");

// Set pointer position
raf.seek(startPos);
// Prepare byte array
byte[] bytes = new byte[(int) (endPos-startPos)];
// read
raf.read(bytes);

// Write new mp3
String newPath = "D:/Java/dx_1.mp3";
File file = new File(newPath);
if (!file.exists()){
	file.createNewFile();
} 

RandomAccessFile newRaf = new RandomAccessFile(file, "rw");
newRaf.write(bytes);

// close resource
raf.close();
newRaf.close();
  • This class is very useful:
    • File breakpoint continuation
    • Combining multithreading: segmented caching of files

3, IO

1. Concept

I: input
O: output

(1) Classification of flow

  • According to the direction of the flow: input flow, and output flow
  • Processing content:
    • Byte stream (mainly used for processing files)
    • Character stream (mainly used for processing text files)
  • Angle of function:
    • Packaging flow
    • Unpackaged flow

(2) Structure of IO

(3) IO four abstract parent classes

classificationinputoutput
byteInputStreamOutputStream
characterReaderWriter

These classes are abstract classes

2. Byte stream

(1) FileInputStream byte input stream

String path = "D:/Java/mm.jpg";
// Input stream object
FileInputStream fileInputStream = new FileInputStream(path);

// Prepare a byte array
byte[] bytes = new byte[1024];
int read;

// The return value of read indicates how many bytes you have read. If it reaches the end of the file, it returns - 1
while ((read = fileInputStream.read(bytes, 0, bytes.length)) != -1){
	// Write the read data to a new file
	
}
// Close flow
fileInputStream.close();

(2) FileOutputStream byte output stream

String path = "D:/Java/mm.jpg";
String newPath = "D:/Java/da_mm.jpg";

// Input stream object
FileInputStream fileInputStream = new FileInputStream(path);
// Prepare an output stream
FileOutputStream fileOutputStream = new FileOutputStream(newPath);

// Prepare a byte array
byte[] bytes = new byte[1024];
int read;

// The return value of read indicates how many bytes you have read. If it reaches the end of the file, it returns - 1
while ((read = fileInputStream.read(bytes, 0, bytes.length)) != -1){
	// Write the read data to a new file
	fileOutputStream.write(bytes, 0, read);
} 

// Close flow
fileInputStream.close();
fileOutputStream.close();

3. Character stream

(1) InputStreamReader character input stream

String path = "D:/Java/FileDemo.java";
String newPath = "D:/Java/FileDemo2.java";

// Build input stream
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(path));

// Prepare buffer array
char[] buffer = new char[1024];
int read;
while ((read = inputStreamReader.read(buffer, 0, buffer.length)) != -1){
	System.out.println(new String(buffer, 0, read));
}

// Close flow
inputStreamReader.close();

(3) OutputStreamWriter character output stream

String path = "D:/Java/FileDemo.java";
String newPath = "D:/Java/FileDemo2.java";

// Build input stream
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(path));
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(newPath));

// Prepare buffer array
char[] buffer = new char[1024];
int read;
while ((read = inputStreamReader.read(buffer, 0, buffer.length)) != -1){
	// System.out.println(new String(buffer, 0, read));
	outputStreamWriter.write(buffer, 0, read);
}

// Close flow
inputStreamReader.close();
outputStreamWriter.close();

4. Object flow

(1) ObjectOutputStream object output stream

Transfer objects in the form of streams on files or networks


Note that the objects to be transferred must implement the Serializable interface.

// Instantiate an object
// If you want to save: Jack's data jack-123123-12
Member jack = new Member("jack", "123123", 12);
Member rose = new Member("rose", "123123", 18);

// Path to store data
String path = "D:/Java/data.txt";
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(path));

objectOutputStream.writeObject(jack);
objectOutputStream.writeObject(rose);

// close
objectOutputStream.close();

(2) ObjectInputStream object input stream

Read the object data stored in the file and deserialize it.

// Path to store data
String path = "D:/Java/data.txt";
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(path));

// read
Member member = (Member) objectInputStream.readObject();
Member member1 = (Member) objectInputStream.readObject();

System.out.println(member);
System.out.println(member1);
objectInputStream.close();
  1. How to store multiple data at one time and read it out at one time:
    Using collections for storage
  2. What if there are properties in an object that do not want to be serialized into a file?
    Add the transient keyword to the corresponding attribute.



5. Buffer flow

Mainly to improve efficiency

  • Character cache input stream
  • Character cache output stream
public static void main(String[] args) throws IOException {
        String path = "D:/Java/FimeDemo.java";
        String newPath = "D:/Java/FimeDemo3.java";

        // Prepare buffer stream
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
        // Buffered output
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newPath)));

        char[] chars = new char[1024];

        int read;

        while ((read = bufferedReader.read(chars, 0, chars.length)) != -1){
            // System.out.println(new String(chars, 0, read));
            bufferedWriter.write(chars, 0, read);
        }

        // Refresh stream
        bufferedWriter.flush();

        // close
        bufferedReader.close();
        bufferedWriter.close();
    }

In the development, we can use the buffer stream and try our best to use the buffer stream, which is more efficient.

Tags: Java Spring JavaSE Eclipse

Posted by Ice on Tue, 21 Sep 2021 02:03:02 +0530