Java Color Base for IO Streaming

Java IO Stream

abnormal

Exceptions and Errors

Throwable

  1. Throwable is a superclass of all Error s and Exception s.
  2. Only direct or indirect subclass objects of Throwable can be thrown by a JAVA virtual machine or JAVA throw.
  3. Similarly, it must be such an object to be a parameter of the catch.

Practical methods:

  1. public String getMessage() returns the throwable's detailed message
  2. public String getLocalizedMessage() returns the localized description of throwable. Subclass override: Generate messages for a specific locale; Subclasses are not overridden: getMessage() is called by default
  3. public String toString() returns a short description of throwablb. The returned content consists of: **Name +':'[colons and spaces] +getLocalizedMessage() of the object, if getLocalizedMessage() returns null, only the name of the object is returned
  4. public void printStackTrace() outputs this throwable and its stack trace information to a standard error stream. [System.err]. The returned content consists of the following: the first row: the object's toString(), after which all rows are stack trace information []fillStackTrace() recorded data]
  5. Public void printStackTrace (PrintStream) output to the specified byte output stream
  6. Public void printStackTrace (PrintStream) output to specified character output stream

Error

  1. Refers to a serious problem that should not be caught by a reasonable procedure.
  2. Error describes a serious problem that is typically not written for code processing but rather corrected and thrown by a JAVA virtual machine.

Exception

  1. Refers to the conditions that a reasonable procedure should capture
  2. Category: RuntimeException and its subclasses, runtime exceptions, compilation can pass, do not require display handling, or can be handled with compilation-time exceptions, otherwise leaving a security hazard. For example: ArithmeticException, where/0 is divided by 0.

P.S.: If there is a RuntimeException, it must be your problem!

  1. Classification: Non-RuntimeException, compilation exception, must be handled, otherwise compilation fails.

No exception checked

In the Java language specification, all exceptions that derive from Error or RuntimeEception are called Unchecked exceptions. [Unchecked exceptions are presumably not checked by the compiler, throw is not thrown, and are ultimately a potential runtime hazard]

When defining a method, try to correct it, or throw it out when you encounter a major error.

Exception Checked

All exceptions except those not checked are called checked [Checked] exceptions. For example, compile-time exceptions

When defining a method, you need to declare not only the return value but also the exception that will be thrown. All checked exceptions that may be thrown should be thrown at the beginning.

exception handling

JVM Default Processing Method

The main main method receives an exception, throws it to the JAVA virtual machine for processing, JVM describes it, encapsulates it as a corresponding exception, and when the specified exception occurs, JVM wraps it as an object corresponding to the exception. And throw it to the caller--main main main method.

Programmer customization

There are two ways to customize processing:

  1. try...catch... Finlly recommends using try alone... Catch and try...finally
  2. Throws throws an exception in the method declaration, leaving it to the caller to handle.

P.S.: Remember not to use try in unnecessary ways or in unnecessary ways. Catch, which causes the exception to be eaten, is the correct way to throw the exception to the caller

Catch Exceptions

Single exception

try{
	// code java
} catch(ExceptionType e){
	// handle for this type
}
  1. Any code in try throws the exception class described in catch. The code following the exception point in the try (the code statement that throws the exception) will not be executed and will instead execute the code in the catch block.
  2. No exceptions were thrown in the try, and the catch will not execute.
  3. An exception occurred in the try. There was no corresponding catch in the catch. The JVM threw the exception and terminated the program.

Multiple Exceptions

try{
	// code java
} catch(ExecptionType e1) {
	// handle for this type
} catch(ExecptionType e2) {
	// handle for this type
} catch(ExecptionType e3) {
	// handle for this type
}
...
  1. e1, e2, e3, and so on, can be directly defined, but the order is irrelevant

JDK 7 New Features (Level Case)

try{
	// code java
} catch(ExceptionType | ... |ExceptionType e ){
	//handle for this type
}

Simple and efficient, there is always only one block of code corresponding to a common catch clause in the byte code file. Note: When multiple exceptions are caught, e is implied as a final variable

  1. When there is a child-parent relationship among e1, e2, e3, catch catches the child exception first, then the parent exception, to prevent: the parent exception eats the child exception.

Principle of exception handling

An exception thrown inside a try is thrown by the JVM, which generates an exception object describing the problem and then throws it, which is matched by the catch. If the exception object of the JVM is an exception instance after a catch, the processing statement block after the catch is executed, otherwise it continues to be thrown to the method, or the main main main method throws it directly. Terminate program running.

Throw\Declare Exceptions

throws ExceptionType,ExceptionType,ExceptionType... When multiple exceptions are thrown, use "," to split.
Undeclarable exception: no exception checked

  1. java internal error
  2. RuntimeException and its subclasses

How do I throw an exception?

  1. Find a suitable exception class
  2. Create an object of this class
  3. Throw Object
/** Runtime Exceptions */
if(target == null){
	throw new NullPointerException([);
}

/** Non-runtime exception [sometimes referred to as compile-time exception] */
// A throws FileNotFoundException declaration must be made on the method
if(!file.exists){
	throw new FileNouFoundException();
}

Be careful:

  1. Runtime exception: throw new ExceptionType(); that will do
  2. Non-runtime exception: throw new ExceptionType(); And must throws ExecptionType in the declaration of the method at the same time

In summary: All checked exceptions should be thrown in the life of a method. Unchecked exceptions are either uncontrollable or should be corrected to avoid occurring. Compilation error if no exception is declared to have been checked.

finally

  1. A finally statement block is bound to execute, regardless of exception capture or failure
  2. Most common when releasing resources [JDBC and IO streams]
  3. If the JVM exits before finally is executed, the finally statement block is not executed. For example: System.exit(0); Executed before finally

//Cleanup resources may also have exceptions

if(target!=null){
	try{
		terget.close();
	} catch(IOException e) {
		// do nothing! Silent shutdown
	}
}
  • Warning: if return statement exists in both try and final, it is defined in final. (Overrides the return statement in try.)

New features of JDK 7

Garbage collection before JDK 7 was too cumbersome. So after JDK 7, there's a new way to release resources: try...with...resource is actually a kind of grammatical sugar.

class Demo7{
	public static void main(String[] args){
		int a = 1;
		int b = 0;
		String str = null;
		try{
			int c = a/b;
			boolean isEquals = str.equals("");
		} catch(NullPointerException | ArthimentException e){
			// handle for this type
		}
	}
}

New features for JDK 7

  1. try...catch(ExecptionType | ExecptionType | ExecptionType... e)
  2. try...with...resources
    public interface Closeable extends AutoCloseable since JDK 5

Interview Questions

The difference between throw and throws?

Answer:

  1. Location is different
  2. Handler is different
  3. Objects are different
  4. Number is different
  5. Possible row differences occur
  • Throw: defined in the method body, for an object that can only be an exception class, indicating that an exception is thrown. There are method body statements to handle it. throw is throwing an exception, and the exception does occur.
  • Throws: Defined on a method declaration, you can target more than one exception class, with a "," in the middle. The exception thrown is declared separated and handled by the method caller. throws represent a possibility that the exception may occur and may not necessarily occur.
  • Cooperative use: When you need to throw a non-runtime exception (compile-time exception), you need to throw a specific exception class object in the method and a throws specific exception class name on the method declaration.

What is the difference between final, fianally and finalize?
Answer:

  1. final ultimately means that variables, methods, classes can be modified
  • Modifier class, can not be inherited
  • Modifier, it cannot be overridden
  • Modifier, then the value cannot be changed [for example, an array, where the address value of the array cannot be modified, but the items of the array can be modified]
  1. A part of finally exception handling used to release resources. In general, the code will be executed unless the JVM exits before the child. For example: Sysem.exit(0)
  2. Method in finalize Object class for garbage collection (called automatically when the garbage collector determines that there is no valid reference to the object)

There is a return statement in the catch. Does the statement in final execute? If so, before or after the catch?
Answer:
finally executes before. Exactly: in the middle. However, final does not change the value of the variable after return. So, return is actually followed by a constant.

class Demo{
	public static void main(String[] args){
		System.out.println(heh());
	}

	public static int heh(){
		int c = 12;		
		try{
			c = 1/0;
		} catch(Exception e){
			return c;
		} finally {
			c = 100
		}
		return c;
	}
}
// The result is: 12
public static int heh()
{
	int i = 12;
	i = 1 / 0;
	i = 100;
	break MISSING_BLOCK_LABEL_27;
	Exception exception;
	exception;
	int j = i;
	i = 100;
	return j;
	Exception exception1;
	exception1;
	i = 100;
	throw exception1;
	return i;
}

File

0: Class Summary

public class File extends Object implements Comparanle<File>

File s are abstract representations of files and folders. (Directory path name)
Instances of the File class are immutable, and once created, the abstract pathname of the File object is immutable.

1: Constractors Summary

Three constructs that are essentially the same:

  1. public File(String pathname)
  2. public File(File parent,String child)
  3. public File(String parent,String child)

2: Methods Summary

  1. Create functionality
    • boolean createNewFile() successfully created file returns true, exists or fails to return false
    • boolean mkdir() creates a single-level path [directory], for example: D:\a\b\c, must already exist a, b, if C is created successfully, returns true, otherwise returns false
    • boolean mkdirs() creates a multilevel directory, such as D:\a\b\c, and creates all non-existent directories in the path, returning true, otherwise returning false
  2. Delete function
    • boolean delete() deletes a file or folder without going to the recycle bin, which is equivalent to Shift + Delete. If it is a folder, it must be empty or false
  3. Rename function
    • boolean renameTo(File dest) path name is the same, rename; Path names are different, cut and rename.
  4. Judgement function
    • boolean isFile() to determine whether it is a file
    • boolean isDirectory() to determine if it is a folder
    • boolean exists() to determine existence
  5. Get Functions
    • public String getAbsolutePath() Gets the absolute path
    • public String getPath() Gets the full path used when creating
    • public String getName() Gets the file name (the file contains the extension)
    • Last modified time of public String lastModified
  6. Advanced Getting Functions
    • public static File[] listRoots() Gets all available drive letters

    • public String[] list() Gets the names of all files and folders in the path

    • public String[] list(FilenameFilter filter) Gets the name of the specified file name under the path

    • public File[] listFiles() Gets a File instance of all files and file names in the path

    • public String[] list(FilenameFilter filter)

    • public String[] list(FileFilter filter)

FilenameFilter Filename Filter

public interface FilenameFilter{
	public abstract boolean accept(File dir,String name);
	// Path where dir was found
	// Name The name of the file found
	// Returns true if and only if the name is in the specified file list
}

FileFilter File Name Filter

public interface FilenameFilter{
	public abstract boolean accept(File pathname);
}

Case 1: Get all under the specified folder. jpg file

File file = new File("D://photo");
String[] subfiles = file.list(new FilenameFilter(){
	@Override
	public abstract accept(File dir,String name){
		return (new File(dir,file).isFile())&&(name.endsWith(".jpg"));
	}
});

Case 2: Bulk Modify File Name

Recursive thinking goes over it again.

Case 3: Get the specified directory and its subdirectories at all levels. ppt file

// FileUtils.list("D://bb","ppt");
public static String[] list(File tar, String extension) {
	if (tar == null || extension == null) {
		throw new NullPointerException("Most not be null");
	}
	if (!tar.exists()) {
		throw new IllegalArgumentException("Dir should be directory");
	}
	if (extension.length() == 0) {
		throw new IllegalArgumentException("");
	}
	if (tar.isFile()) {
		if (tar.getName().endsWith(extension)) {
			return new String[] { tar.getPath() };
		} else {
			return null;
		}
	}
	return traverse(tar, extension, new StringBuilder());
}

private static String[] traverse(File dir, String extension,
		StringBuilder sb) {
	File[] files = dir.listFiles();
	for (File subfile : files) {
		if (subfile.isFile()) {
			// Remember to ignore the case of suffix names
			if (subfile.getName().toLowerCase()
					.endsWith(extension.toLowerCase())) {
				sb.append(subfile.getPath()).append("<>");
			}
		} else {
			traverse(subfile, extension, sb);
		}
	}
	return sb.toString().split("<>");
}

Case 4: Delete the specified directory (which may contain subdirectories)

FileUtils.delete();

FileUtils.class

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-QN4am2BT-1651420720769)(./1443874610554.png)]

package com.io.exec;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtils {

	private static final int DEFAULT_BUFFER_SIZE = 8192;

	public static void delete(File target) throws FileNotFoundException {
		if (target == null) {
			throw new NullPointerException("Directory most not be null");
		}
		if (!target.exists()) {
			throw new FileNotFoundException("srcDir cannot be find");
		}
		if (target.isFile()) {
			// If it's a file, delete it and you're done
			System.out.println("\t" + target.getName() + "    "
					+ target.delete());
			return;
		}
		// Get the files, folders used in the directory
		File[] files = target.listFiles();
		for (File subfile : files) {
			if (subfile.isFile()) {
				// If it is a file, delete it directly
				System.out.println("\t" + subfile.getName() + "    "
						+ subfile.delete());
			} else {
				delete(subfile);
			}
		}
		// Deleting all files has been implemented in the delete empty folder for loop
		System.out.println(target.getName() + "    " + target.delete());
	}

	public static void copyDir(File srcDir, File destDir) throws IOException {
		copyDir(srcDir, destDir, DEFAULT_BUFFER_SIZE);
	}

	public static void copyDir(File srcDir, File destDir, int bufferSize)
			throws IOException {
		if (srcDir == null || destDir == null) {
			throw new NullPointerException("srcDir most not be null");
		}
		if (!srcDir.exists()) {
			throw new FileNotFoundException("srcDir cannot be find");
		}
		if (!srcDir.isDirectory()) {
			throw new IllegalArgumentException("srcDir should be a directory");
		}
		File[] files = srcDir.listFiles();
		for (File subfile : files) {
			File src = subfile;
			File dest = new File(destDir, subfile.getName());
			if (subfile.isFile()) {
				copyFile(src, dest, bufferSize);
			} else {
				copyDir(src, dest, bufferSize);
			}
		}
	}

	public static void moveAndRename(File srcDir, File destDir, String srcEnds,
			String destEnds) throws IOException {
		moveAndRename(srcDir, destDir, srcEnds, destEnds, DEFAULT_BUFFER_SIZE);
	}

	public static void moveAndRename(File srcDir, File destDir, String srcEnds,
			String destEnds, int bufferSize) throws IOException {
		if (srcDir == null || destDir == null) {
			throw new NullPointerException("srcDir most not be null");
		}
		if (!srcDir.exists()) {
			throw new FileNotFoundException("srcDir cannot be find");
		}
		if (!srcDir.isDirectory()) {
			throw new IllegalArgumentException("srcDir should be a directory");
		}
		File[] files = srcDir.listFiles();
		for (File subfile : files) {
			File src = subfile;
			File dest;
			if (subfile.isFile()) {
				if (subfile.getName().endsWith(srcEnds)) {
					dest = new File(destDir, subfile.getName().replace(srcEnds,
							destEnds));
					copyFile(src, dest, bufferSize);
				}
			} else {
				dest = new File(destDir, subfile.getName());
				copyDir(src, dest, bufferSize);
			}
		}
	}

	public static void copyFile(File srcFile, File destFile) throws IOException {
		copyFile(srcFile, destFile, DEFAULT_BUFFER_SIZE);
	}

	public static void copyFile(File srcFile, File destFile, int bufferSize)
			throws IOException {
		if (srcFile == null || destFile == null) {
			throw new NullPointerException("srcFile most not be null");
		}
		if (!srcFile.exists()) {
			throw new FileNotFoundException("srcFile cannot be find");
		}
		if (!srcFile.isFile()) {
			throw new IllegalArgumentException("srcFile should be a file");
		}
		File destDir = destFile.getParentFile();
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(srcFile);
			out = new FileOutputStream(destFile);
			byte[] bys = new byte[bufferSize];
			int len;
			while ((len = in.read(bys)) >= 0) {
				out.write(bys, 0, len);
			}
		} finally {
			IOUtils.closeQuietly(out);
			IOUtils.closeQuietly(in);
		}
	}

	public static String[] list(File tar, String extension) {
		if (tar == null || extension == null) {
			throw new NullPointerException("Most not be null");
		}
		if (!tar.exists()) {
			throw new IllegalArgumentException("Dir should be directory");
		}
		if (extension.length() == 0) {
			throw new IllegalArgumentException("");
		}
		if (tar.isFile()) {
			if (tar.getName().endsWith(extension)) {
				return new String[] { tar.getPath() };
			} else {
				return null;
			}
		}
		return traverse(tar, extension, new StringBuilder());
	}

	private static String[] traverse(File dir, String extension,
			StringBuilder sb) {
		File[] files = dir.listFiles();
		for (File subfile : files) {
			if (subfile.isFile()) {
				// Remember to ignore the case of suffix names
				if (subfile.getName().toLowerCase()
						.endsWith(extension.toLowerCase())) {
					sb.append(subfile.getPath()).append("<>");
				}
			} else {
				traverse(subfile, extension, sb);
			}
		}
		return sb.toString().split("<>");
	}
}

I/O Stream

0: Class Summary

  1. IO streams are used to process data transfers between devices: upload and download
  2. JAVA operates on data through streaming
  3. The objects that JAVA uses to manipulate streams are all in java. Under IO package

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-8aUTRDu3-1651420720771)(./1443866080616.png)]
All the specific subclasses used are derived from this four-base class with this suffix.

1: Constractors Summary

  1. When constructing objects, it is strongly recommended to use parent and interface references to objects pointing to subclasses
    Provides a parameterless construction method in the parent class, interface, for use when initializing specific subclasses
  • public InputStream(){}
    public OutputStream(){}
  • InputStream in = new FileInputStream(File file)
    InputStream in = new FileInputStream(String pathname)
  • Reader & Writer, FileReader & FileWriter Same as above
  1. An efficient buffer stream corresponding to a base stream that wraps the base stream and provides a buffer
  • BufferedInputStream buffIn = new BufferedInputStream(InputStream in)
    BufferedInputStream buffIn = new BufferedInputStream(InputStream in,int size)
    The default buffer size is 8192 bytes, you can specify it yourself, recommend 1M, but specify it according to your own computer performance, my computer testing 128K is the best
  • Reader & Writer, FileReader & FileWriter Same as above
  1. Convert stream, wrap byte stream to character stream, and specify encoding without specifying default platform encoding
  • Reader reader = new InputStreamReader(InputStream in)
    Reader reader = new InputStreamReader(InputStream in,String charsetname)
    Reader reader = new InputStreamReader(InputStream in,Charset charset)

Case study: Creating an efficient character buffer stream to copy text files

InputStream in = null;
Reader reader = null;
BufferedReader buffReader = null;

OutputStream out = null;
Writer writer = null;
BufferedWriter = null;

try{
	in = new FileInputStream("D://joian.info");
	reader = new InputStreamReader(in);
	buffReader = newq BufferedReader(reader);

	out = new FileOutputStream("D://Sun.info");
	writer = new OutputStream(out);
	buffWriter = new BufferedWriter(writer);
	
	// Each line while reading
	String line;
	while((line = buffReader.readLine())!=null){
		// handle each line. write...
		buffWriter.write(line);
		buffWriter.newLine();
		buffWriter.flush();
	}
} catch(FileNotFoundException e){
	System.out.println("File not found...:"+e.getMessaqge());
} catch(IOException e){
	System.out.println("Errors while readint file...:"+e.getMessaqge());
} finally {
	// The principle of closure is:
		// From the output stream to the input stream, "It doesn't matter"
		// From Dependency to Dependency Order
	IOUtils.closeQuietly(buffWriter);
	IOUtils.closeQuietly(writer);
	IOUtils.closeQuietly(out);

	IOUtils.closeQuietly(buffReader);
	IOUtils.closeQuietly(reader);
	IOUtils.closeQuietly(in);
}

2: Methods Summary

Read-write defaults to a single byte or character. Using a byte array or character array, you can specify the number of bytes or characters to read and write each time, thereby reducing command requests to the bottom, reducing interaction with the bottom of the system, and improving read-write efficiency.

  1. Read function
    Input stream method for writing from outside to program

    • Reading methods for byte streams: InputStream, FileInputStream, BufferedInputStream
      [External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-sjWcjrEx-1651420720772)(./1443929895703.png)]

    • Reader, InputStreamReader
      [External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-4x8v8pzS-1651420720773)(./1443930052053.png)]

    • An efficient way to read buffered character streams: BufferedReader
      [External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-T9TbVwMW-1651420720775)(./1443930692719.png)]
  2. Write function
    Output Stream Method for Writing Out Programs

    • Writing methods for byte streams: OutputStream, FileOutputStream, BufferedOutputStream
      [External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-b6LhGVhJ-1651420720776)(./1443930530945.png)]

    • Writing methods for character streams: Writer, OutputStreamWriter
      [External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-xtoubxbj-1651420720778)(./1443930618467.png)]

    • Efficient writing method for buffering character streams: BufferedWriter
      [External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-1nJyPwy0-1651420720779)(./1443930644970.png)]
  3. Additional function
    When writing out, append is true for the second parameter of the specified constructor, which defaults to false: empty, write.

  4. Turn off function

  • implements Closeable
    public interface Closeable extends AutoCloseable since JDK 5
    Only an abstract void close() throws IOException method is provided for specific subclasses to implement. If this method has been used to close the operation, there is no effect when the call is called again. The operation of IO stream, whether read or write, requires the closure of the execution resource at the end of the operation to release the related system resources. Otherwise, the execution efficiency will be greatly reduced and the security will be affected. Close does two main things: 1. Let the streaming objects become garbage, the sad two and the recycler recycle; 2. Notify the system to release all flow-related resources

Case study: Simple implementation of file read/write [using byte stream]

InputStream in = null;
OutputStream out = null;
try{
	in = new FileInputStream("D://Joian.info");
	out = new FileOutputStream("D://Sun.info");
	
	// Create Array Buffer
	byte[] bys = new byte[128*1024]; // 1024*1024
	int len;
	while((len = in.read(bys))>=0) // Become paranoid and don't want to believe -1
	{
		out.write(bys,0,len);
		// out.write(len);
		// write method with three parameters is recommended
		// The last character read in by the buffer is len
		// The interval content of [len,bys.length-1] was the last top-notch content
		// Has been written to the file, in writing, causing duplication.
	}
} catch(FileNotFoundException e){
	System.out.println("File not found...:"+e.getMessaqge());
} catch(IOException e){
	System.out.println("Errors while readint file...:"+e.getMessaqge());
} finally {
	// Closing principle
	IOUtils.closeQuietly(out);
	IOUtils.closeQuietly(in);
}

3: How to achieve

output stream

  1. Create Output Stream Object
    • Call system functions to create files (yes, no)
      Trigger the exception FileNotFoundException if a directory does not exist in the path
    • Create a specific subclass (FileOutputStream fos) object of the output stream
    • Associate fos with file
  2. Call stream method write() for write
  3. Close Stream Object

Input stream

  1. Create Input Stream
    • Associate the created input stream object with the system file and throw the exception FileNotFoundException if no specified file exists
  2. Call stream method read() to read
  3. Close Stream Object

Create Stream Object

  1. Create Stream Object Specify null Initialization
    • The constructor may throw a FileNotFoundException exception when creating a stream object
    • Statements in the try clause may not execute, but in finally you need to close the stream object and initialize it first
  2. Parent\Interface References Point to Subclass Objects - Polymorphism

Implement Line Break

  1. The Windows system line break is'\n'
  2. Linux\Unix system line break is "\r\n"
  3. The Windows system line break is'\r'

Chinese characters

Chinese characters occupy two byte lengths in the computer and can be stored using the character char type: GBK encoding uses two bytes

  • The first byte is negative (fixed) (dominant)
  • The second byte is usually negative or may be positive (variable)

When encoding, the length of encoding bytes is different according to different encoding methods:

  • ASCII encoding: 1 byte
  • GBK encoding: 2 bytes
  • UTF-8 encoding: 3 bytes
  • Unicode encoding: UTF-16, 4 bytes by default

Character streaming relies on byte streaming: two byte lengths are read at a time and converted to characters according to a given or default encoding.

// Custom Byte Stream Reads Chinese Characters Correctly
// Read another byte when the last read byte is found to be negative
// Simple implementation, possibly with different encodings

Scrambling Problem

Read and write with the same code...

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-graDyvxh-1651420720780)(./1443934219363.png)]

Coding table

Definition:

  1. Code table: A code description table to help users understand what data and character codes mean. Composed of real-world characters and corresponding numeric values
  2. Computer coding: Computer does not represent the way characters and numbers are encoded. The minimum unit is byte bit, and the unit of machine language is byte. 1 byte = 8 bits

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-d5FdpyYa-1651420720781)(./1443934851581.png)]

  1. ANSI: A variety of Chinese character extension encoding methods in which two bytes represent a character
  • ANSI in Simplified Chinese Operating System stands for GB2312 | GBK
  • Day is the JISI encoding represented by ANSI in the operating system
  1. ASCII: American Standard Code for Information Exchange, representing a range of'-128-127', consisting of 8 bits (single byte), with the highest bits being the sign bits and the remaining 7 being the numeric digits

  2. ISO-8859-1: European code table, Latin code table, expressed in the range of "0-255", composed of 8 bits (single byte), are all numeric bits

  3. GB2312: Simplified Chinese character set, 99.75% coverage. Double byte

  • High-bit bytes: 0xA1-0xF7 (01-87 zone)
  • Low bit bytes: 0xA1~0xFE (01~94 bits)
  • For example, "Ah" corresponds to a 16-region 01 bit expressed as: 0xB0A1 (hexadecimal)
  1. GBK: Character set extends GB2312 to support Traditional Chinese
  2. GB18030: Characters are encoded in single, double, and four bytes
  • Single byte corresponds to ASCII code table
  • PS:GB2312, GBK, GB18030 are collectively referred to as double-byte character sets (DBCS)
  • GB18030-2000 Latest Complete Coding Standard for Chinese Characters
  1. Big-5 Code: Big Five Code, a traditional font encoding scheme commonly used in Taiwan and Hong Kong
  2. Encoding method for Unicode:JAVA. International Standard Code, the latest version of Unicode 8.0, is short for the universal Multi-octet encoded character set. Uniform and unique encoding binary encoding is set for each character in each language to meet the processing requirements for text conversion across languages and platforms.
    Unicode hexadecimal encoding "U+", fixed to use 16bits to represent a character, standard Unicode is called UTF-16. Later, UTF-8 emerged to enable the transfer of double-byte Unicode on existing systems that handle single-byte data, encoding Unicode in a manner similar to MBCS (Multiple-Byte Character System, GB2312).
  3. UTF-8 uses up to three bytes to represent a character, defines interval rules, and is maximally compatible with ASCII
  • Single byte: 00000000 - 0000007F
  • Double bytes: 00000080 - 000007FF
  • Three bytes: 00000800 - 0000FFFF

Coding-related methods in String classes

Use platform default encoding when no encoding is provided

  1. public String(byte[] bys,Charset cs)
  2. public String(byte[] bys,String cs)
  3. public byte[] getBytes(Charset cs)
  4. public byte[] getBytes(String cs)

Legacy class - Properties

public class Properties extends Hashtable<Object,Object>

0: Class Summary

  1. Attribute collection class, which can be used in conjunction with IO, is persistent and can be saved in or loaded from the stream. Keys and corresponding values are strings
  2. This class is thread-safe and multithreads can share a Properties object without external synchronization.

1: Constractors Summary

  1. public Properties()
  2. public Properties(Properties defaults) uses protected field values Properties defaults to construct attribute collection objects

2: Methods Summary

Method inherited from Hashtable (rarely used, for understanding only).
Special features:

  • public Object setProperty(String key, String value) calls the put method implementation of Hashtable. Returns the old value of the specified key, or null if the key does not exist
  • public String getProperty(String key) returns the value of the specified key. If the specified key does not exist, it returns null
  • Public Set <String> stringPropertyNames() Collection of return keys

Properties with IO:

  • public void load(InputStream in) throw IOException
  • public void load(Reader reader) throw IOException
    A row-oriented format reads a list of attributes from the input character stream and reads data (key-value pairs) from a file into a collection, specifically an attribute collection Properties object. Row data should be in one of three formats: (the split symbols are =,:, -)
  1. key = value
  2. key : value
  3. key - value
  • public void store(OutputStream out, String comments) throw IOException
  • public void store(Writer writer, String comments) throw IOException
    Store the data in the collection in a file in the format ** "key=value"**, with comments as a description of the list of attributes.
    • comments is null: just add # + new Date() to the first line
    • Comments are not null: you need to add a line # + comments before # + new Date()

      [External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-R6lwzoe8-1651420720783)(./1443957921724.png)]

IOUtils.class

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-3298WCaC-1651420720783)(./1443866826101.png)]

package com.io.exec;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;

public class IOUtils {

	// Because Closable is implemented in the stream class definition
	// Closeable inherits from AutoCloseable after JDK 1.5
	public static void closeQuietly(Closeable target) {
		// public static void closeQuietly(AutoCloseable target) {
		if (target != null) {
			try {
				target.close();
			} catch (IOException e) {
				// do nothing! Silent shutdown
			}
		}
	}

	/**
	 * Provide a simple way to copy files
	 */
	public static void copy(Reader reader, Writer writer, int bufferSize)
			throws IOException {
		// An exception from the program is thrown to the caller, who can handle it.
		// Do a simple test
		if (reader == null || writer == null) {
			throw new NullPointerException("Stream cannot be null!");
		}
		if (bufferSize <= 0) {
			throw new IllegalArgumentException(
					"BufferSize should be positive readerteger!");
		}
		int len;
		char[] chs = new char[bufferSize];
		while ((len = reader.read(chs)) > 0) {
			writer.write(chs, 0, len);
			writer.flush();
		}
	}

	public static void copy(Reader reader, Writer writer) throws IOException {
		copy(reader, writer, 1024 * 1024);
	}

	public static void copy(InputStream in, OutputStream out, int bufferSize)
			throws IOException {
		// An exception from the program is thrown to the caller, who can handle it.
		// Do a simple test
		if (in == null || out == null) {
			throw new NullPointerException("Stream cannot be null!");
		}
		if (bufferSize <= 0) {
			throw new IllegalArgumentException(
					"BufferSize should be positive integer!");
		}
		int len;
		byte[] b = new byte[bufferSize];
		while ((len = in.read(b)) > 0) {
			out.write(b, 0, len);
		}
	}

	public static void copy(InputStream in, OutputStream out)
			throws IOException {
		copy(in, out, 1024 * 1024);
	}

	/***
	 * Implements downloading and reading files from url paths according to the encoding given by the platform
	 * 
	 * @param url
	 *            The url path used for the given Download
	 * @return A string of text content read in the specified encoding
	 * @throws IOException
	 */
	public static String downloadString(URL url) throws IOException {
		/** Throw an exception on to the caller for handling... */
		// Use the same encoding as the platform by default when reading encoding from the system configuration file
		// return downloadString(url, System.getProperty("file.encoding"));
		return downloadString(url, System.getProperty("sun.jnu.encoding"));
	}

	/***
	 * Implements downloading and reading files from a url path in the specified encoding format
	 * 
	 * @param url
	 *            The url path used for the given Download
	 * @param charset
	 *            Specify parsed encoding
	 * @return A string of text content read in the specified encoding
	 * @throws IOException
	 */
	public static String downloadString(URL url, String charset)
			throws IOException {
		/** Because highly cached character streams depend on character streams, character streams depend on byte streams, created at once */
		/** Define using an interface to reference a specific subclass object */
		InputStream in = null;
		Reader reader = null;
		BufferedReader buffReader = null;

		// String Builder single-threaded and efficient string creator is used because reading text files or web page sources requires multiple string splicing operations
		StringBuilder sb = new StringBuilder();
		try {
			/** Calling openStream of the url object converts the specified url address to a byte input stream */
			in = url.openStream();
			/** Read a character stream using a specific read-to-convert stream with a given encoding */
			/** A character stream can be thought of as a byte stream + encoding table */
			reader = new InputStreamReader(in, charset);
			/** Building efficient character streams */
			buffReader = new BufferedReader(reader);
			/** Create a string to read each line of text */
			String line;
			/** Loop to get each line in the file, null to indicate the end of the text read */
			while ((line = buffReader.readLine()) != null) {
				/** Add using StringBuilder's append add method */
				sb.append(line).append("\n");
			}
		} finally {
			/** Close Order: Close upper dependencies before lower dependencies */
			IOUtils.closeQuietly(buffReader);
			IOUtils.closeQuietly(reader);
			IOUtils.closeQuietly(in);
		}
		/** Return value using toString method of StringBuilder */
		return sb.toString();
	}

	/**
	 * Implements reading text files in a specified encoding
	 * 
	 * @param file
	 *            Text files that need to be read
	 * @param charset
	 *            Specified Reading Method
	 * @return Returns a string of text content read in the specified encoding
	 */
	public static String readTextFile(String file, String charset)
			throws IOException {
		/** String Builder single-threaded and efficient string creator is used because reading text files or web page sources requires multiple string splicing operations */
		StringBuilder sb = new StringBuilder();
		InputStream fis = null;
		Reader reader = null;
		BufferedReader buffReader = null;
		try {
			/** Create byte input stream using given file path */
			fis = new FileInputStream(file);
			/** Read a character stream using a specific read-to-convert stream with a given encoding */
			/** A character stream can be thought of as a byte stream + encoding table */
			reader = new InputStreamReader(fis, charset);
			/** Building efficient character streams */
			buffReader = new BufferedReader(reader);
			/** Create a string to read each line of text */
			String line;
			/** Loop to get each line in the file, null to indicate the end of the text read */
			while ((line = buffReader.readLine()) != null) {
				/** Add using StringBuilder's append add method */
				sb.append(line).append("\n");
			}
		} finally {
			/** Close Order: Close upper dependencies before lower dependencies */
			IOUtils.closeQuietly(buffReader);
			IOUtils.closeQuietly(reader);
			IOUtils.closeQuietly(fis);
		}
		/** Return value using toString method of StringBuilder */
		return sb.toString();
	}

	/**
	 * Implement text file reading by default encoding
	 * 
	 * @param file
	 *            Text files that need to be read
	 * @return Returns a string of text content read in default encoding
	 */
	public static String readTextFile(String file) throws IOException {
		/** Throw an exception on to the caller for handling... */
		// Use the same encoding as the platform by default when reading encoding from the system configuration file
		// return readTextFile(file, System.getProperty("file.encoding"));
		return readTextFile(file, System.getProperty("sun.jnu.encoding"));
	}
}

Interview Questions

The difference between close and flush methods?

Thematic Lessons

A child cannot be worse than a parent

  1. When a child class overrides a parent method, it must throw a child exception with the same or parent exception
  2. Multiple exceptions of the parent class, subclasses can be the same, but exceptions not thrown by the parent class
  3. If the parent class has no exceptions, the child class cannot throw exceptions. If the child class has exceptions, only try cannot throws.

How to access resource files in the src directory

Traditional ways of loading resources

Using the class attribute of the current class, call getResource(String path); Method implementation

URL url = 
	Demo.class.getResource("/a.txt");
// perhaps
	Demo.class.getResource("/com/rupeng/a.txt")

Class Loader Load Resources

When using the class loader to load resources, remember not to start with'/'.

URL url = 
	Demo.class.getClassLoader().getResource("a.txt");
// perhaps
	Demo.class.getClassLoader().getResource("com/rupeng/bin/a.txt");

Comprehensive case:

package com.io.src;

import java.io.InputStream;
import java.io.IOException;
import java.net.URL;

public class Demo1 {
	public static void main(String[] args) {
		// Accessing resource files in the src directory
		/** When the resource file is under the src folder */
		// URL url = Demo1.class.getResource("/a.txt");
		URL url = Demo1.class.getClassLoader().getResource("a.txt");
		/** When the resource file is under the same package (folder) as the class */
		// URL url = Demo1.class.getResource("/com/io/src/a.txt");
		// URL url =
		// Demo1.class.getClassLoader().getResource("com/io/src/a.txt");
		/** Convert resources directly to byte streaming */
		InputStream inStream = Demo1.class.getClassLoader()
				.getResourceAsStream("a.txt");
		/**
		 * When obtained using the getResource method of the class attribute, you must add'/'to the getResource method using the class loader or
		 * getResourceAsStream When fetching, do not add'/'
		 */
		// Specific reason: use Demo1.class.getClassLoader().getResource("); So you know
		System.out.println(Demo1.class.getClassLoader().getResource(""));
		// file:/C:/JavaProject/26_IO/bin/
		System.out.println(Demo1.class.getResource(""));
		// file:/C:/JavaProject/26_IO/bin/com/io/src/
		try {
			// InputStream in = url.openStream();
			InputStream in = inStream;

			byte[] bys = new byte[10];
			StringBuilder sb = new StringBuilder();
			while (in.read(bys) >= 0) {
				sb.append(new String(bys));
			}
			System.out.println(sb);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Tags: Java

Posted by tnewton on Mon, 02 May 2022 00:28:29 +0300