Flow and file
8.1 the File type
The File class can operate on files and directories. These methods are most commonly used throughout the File class: Constructor :public File(String pathName) Delete a File :public Boolean Delete () Check whether the File exists :public Boolean exists() Create a directory :public Boolean Mkdirs () public file getParentFile() The pathname is a local path. The File class object can represent a specific File or a directory. The File class can obtain information about the File, such as the size of the File, but cannot process the content of the File
8.2 the flow
8.2.1 profile
Java I/O mechanisms are based on data streams for input and output, which can be divided into the following aspects: ① According to the direction of data flow: input stream and output stream ② according to the unit of data processing: byte stream (1byte = 8bit) and character stream (1char = 2byte = 16bit) ③ According to the function: node stream (program directly reads and writes data on the data source) and processing stream (packaged in the process) Most of the classes in the IO package derive from the following four abstract classes:
Byte stream | Characters of the flow | |
The input stream | InputStream | Reader |
The output stream | OutputStream | Writer |
8.2.2 InputStream and OutputStream
InputStream and OutputStream are byte-oriented I/ OS that support only 8-bit byte streams. InputStream indicates that the input data sources include: ① Byte arrays ② strings ③ files ④ pipes ⑤ sequences of other kinds of streams ⑥ Other data sources, such as Internet connections, etc
OutputStream indicates that the output targets include: ① byte array ② file ③ pipe
InputStream and OutputStream hierarchies:
8.2.3 Reader and Writer
Reader corresponds to Writer, which is a character-oriented form of I/O compatible Unicode node stream:
Byte stream | Characters of the flow |
InputStream / OutputStream | Reader / Writer Adapter: InputStreamReader/OutputStreamWriter |
FileInputStream / FileOutputStream | FileReader / FileWriter |
StringBufferInputStream(deprecated)/(no corresponding class) | StringReader / StringWriter |
ByteArrayInputStream/ByteArrayOutputStream | CharArrayReader / CharArrayWriter |
PipedInputStream / PipedOutputStream | PipedReader / PipedWriter |
Byte stream | Characters of the flow |
FilterInputStream / FilterOutputStream | FilterReader/FilterWriter(Abstract class, no subclasses) |
BufferedInputStream / BufferedOutputStream | BufferedReader(with readLine())/BufferedWriter |
PrintStream | PrintWriter |
LineNumberInputStream(deprecated) | LineNumberReader |
PushbackInputStream | PushbackReader |
8.3 the sample
8.3.1 File Operations
As to read the file
public static String readFile(String fileName) { File file = new File(fileName).getAbsoluteFile(); if (! file.isFile()) { return ""; } StringBuilder sb = new StringBuilder(); try (InputStreamReader isr = new InputStreamReader(new
FileInputStream(file), "UTF-8"); BufferedReader br = new BufferedReader(isr)) { String str; while ((str = br.readLine()) ! = null) { sb.append(str).append("\r\n"); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); }Copy the code
As written documents
public static void writeFile(String fileName, String msg) {
File file = new File(fileName);
try {
BufferedWriter bf = null;
try {
bf = new BufferedWriter(new FileWriter(file, true));
bf.write(msg);
bf.newLine();
bf.write(msg);
} finally {
if (bf != null) {
bf.flush();
bf.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
Copy the code
8.3.2 Memory Operations
public static void memoryOpt(){ String msg = "hello world !!!" ; try(InputStream in = new ByteArrayInputStream(msg.getBytes()); OutputStream out = new ByteArrayOutputStream();) { int temp = 0; while((temp = in.read()) ! = -1){ out.write(Character.toUpperCase(temp)); } System.out.println(out); } catch (IOException e) { e.printStackTrace(); }}Copy the code
8.3.3 are included pipe flow
static class Writer implements Runnable { PipedOutputStream out; public Writer(PipedOutputStream out) { this.out = out; } @Override public void run() { try { String message = "I'm K^Joker"; try { out.write(message.getBytes()); } finally { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } static class Reader implements Runnable { PipedInputStream in; public Reader(PipedInputStream in) { this.in = in; } @Override public void run() { byte data[] = new byte[1024]; try { try { int len = in.read(data); System.out.println(new String(data, 0, len)); } finally { in.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { PipedOutputStream out = new PipedOutputStream(); PipedInputStream in; try { in = new PipedInputStream(out); Thread read = new Thread(new Reader(in)); Thread write = new Thread(new Writer(out)); read.start(); write.start(); } catch (IOException e) { e.printStackTrace(); }}Copy the code
8.3.4 object flow
public class Person implements Serializable { private String name; private transient Integer age; private final Integer height = 180; private static Integer weight = 160; Private TRANSIENT final String nickName = "booty "; private transient static String phone = "110"; public Person(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", height=" + height + ", nickName='" + nickName + '\'' + '}'; } public static void serialize() { File file = new File("E:" + File.separator + "serializable.txt"); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) { out.writeObject(new Person("K^Joker", 23)); } catch (IOException e) { e.printStackTrace(); } } public static void deserialize() { File file = new File("E:" + File.separator + "serializable.txt"); try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));) { Object obj = in.readObject(); System.out.println(obj); } catch (IOException e){ e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { // serialize(); deserialize(); }}Copy the code
Nine, the enumeration
9.1 features
① Enumerations are often used to represent a set of constants of the same type, such as gender, education, and date. Enumeration is a special class, it is the same as ordinary class, but the constructor access modifier can only be private, enum keyword definition, default inherit java.lang.Enum class, so can not inherit other classes. Java.lang. Seriablizable and java.lang.Comparable are supported. All enumeration values are public static final and must be defined in the first line. ⑤ If an abstract method is defined in the enumeration, all enumeration variables must implement the abstract method
9.2 Implementation Mechanism
Let’s start by defining an enumeration:
public enum ColorEnum {
RED(), YELLOW(), BLUE();
}
Copy the code
Javac compiles and generates.class files:
We can see that the constructor generated by the compiler is private by default, and javap looks at the compiled bytecode:
We can see that the enumeration is actually a class that is declared final, inheriting the Enum class. The variables defined by the enumeration are declared public static final, plus static code blocks, and two static methods values() and valueOf(). The Enum class is an abstract class with two main attributes, name(the name of the enumeration variable) and ordinal(the index of the position of the enumeration variable). It does something like this in an extra static block of code:
RED = new ColorEnum("RED", 0);
YELLOW = new ColorEnum("YELLOW", 1);
BLUE = NEW ColorEnum("BLUE", 2);
$VALUES = new ColorEnum[]{RED, YELLOW, BLUE};
Copy the code
The values() method returns a copy of the $values array, and the valueOf method returns the corresponding enumeration instance based on the variable name passed in. We can get a sense of this from the graph below.
9.3 Enumeration Use
① Enumerations can implement interfaces and have abstract methods
Public enum ColorEnum implements ColorInterface{RED(" RED "){@override void say(){system.out.println (" I am RED "); }}, @override void say(){system.out.println (" I am YELLOW "); }}, @override void say(){system.out.println (" I am BLUE "); }}; // Must be the first line private String color; private ColorEnum(String color){ this.color = color; } @Override public String getColor(){ return color; } abstract void say(); public static void main(String[] args) { System.out.println(ColorEnum.RED); //RED System.out.println(ColorEnum.RED.getColor()); / / RED System. Out. Println (ColorEnum. RED. The name ()); //RED System.out.println(ColorEnum.RED.ordinal()); //0 for(ColorEnum color : ColorEnum.values()){ System.out.println(color); //RED YELLOW BLUE } ColorEnum.RED.say(); I am red}}Copy the code
② Enumeration is used on interfaces
public interface Food {
enum Appetizer implements Food{
SALAD, SOUP, SPRING_ROLLS;
}
enum Dessert implements Food{
FRUIT, TIRAMISU, GELATO
}
}
Copy the code
Ten, annotations,
10.1 Basic Notes
Under the java.lang package, Java has five built-in annotations ① @override to indicate that the current method definition will Override methods in the superclass. The compiler will raise an error if the method signature does not match the overridden method. @override will only apply to the method. The compiler will issue a warning message. ③ @SuppressWarnings closes an improper compiler warning message ④ @Safevarargs disables heap contamination warning ⑤ @functionalIterface Declare an interface as a functional interface (a functional interface contains only one abstract method)
10.2 Custom Annotations
10.2.1 yuan notes
@Target | To indicate where the annotation can be used, its ElementType parameters include: CONSTRUCTOR: the declaration of a CONSTRUCTOR FIELD: FIELD declaration (including enum instances) LOCAL_VARIABLE: local variable declaration METHOD: indicates the METHOD declaration PACKAGE: a PACKAGE declaration PARAMTER: indicates the parameter declaration TYPE: Class, interface (including annotation TYPE), or enum declaration |
@Retention | Indicates the level at which the annotation information needs to be saved, and its RetentionPolicy parameters include: SOURCE: Annotations will be lost by the compiler CLASS: Annotations are available in the CLASS file, but are lost by the JVM RUNTIME: The JVM is RUNTIME and can read the annotated information through reflection |
@Documented | Include this annotation in Javadoc |
@Inherited | Allows subclasses to inherit annotations from their parent class |
10.2.2 rules
Annotation elements can be of the following types: ① All basic data types ② String ③ Class type ④ Annotation ⑤ All of the above types of arrays note: Using the @ interface custom annotations, inherited the default Java lang. The annotation. The annotation, only with a public or default the two access modifiers, if only one parameter, had better set the parameter name for “value”, annotation does not support inheritance, can be nested.
10.2.3 sample
Public class Person {@myValidation (nullable = false, message = "null ") private String name; public Person(){ } public Person(String name) { this.name = name; } } @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface MyValidation { boolean nullable() default true; String message() default ""; } public class Validation { public void validate(Object object) throws Exception { Class obj = object.getClass(); Field[] fields = obj.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); verify(field, object); field.setAccessible(false); } } private void verify(Field field, Object object) throws Exception { MyValidation mv = field.getAnnotation(MyValidation.class); if (mv ! = null && ! mv.nullable()) { Object name = field.get(object); if("".equals(name) || name == null){ throw new Exception(mv.message()); } } } public static void main(String[] args) throws Exception { Validation v = new Validation(); // v.validate(new Person("")); v.validate(new Person()); }}Copy the code
11. Conclusion
With reference to Thinking in Java and Java Core, there are a lot of things left unwritten about the entire Java foundation such as reflection, NIO, JUC, collections, etc. CTRL + O: View the properties and methods of the current class ② CTRL + H: global search ③ CTRL + F: current file search ④ Alt+←/→ : ⑤ CTRL + Shift + F: Format (not all formatting, otherwise code View is very…) ⑦ Ctrl+ t: find the implementation class directly from the interface. ⑧ f6/f8: Debug Next/next breakpoint ⑨ CTRL + Shift + R: open the resource list ⑩ Alt +/: automatically complete the code or alert the code, and therefore delete the current line