IO stream objects

The File type

File: a folder in a computer that stores data (music, movie, word) Directory: a folder that cannot store data, a container that protects files Path: the location of files and directories in the computer Java.io.File class: Files and directories and paths, objects, methods of the File class, operation object File class is platform-independent: Windows, Linux, Mac

Constructor of the File class

URI: Uniform Resource Identifier (URIS), which contains both urls and non-URLS. URL: Uniform Resource Locator (URIs), which is the Internet address protocol :// Domain name www.baidu.com

File(String path) The String argument must be a path. The String path becomes the File object File(String parent,String Child) Parent Parent path of the String type, child String subpath. Absolute path: A path is unique in a computer. Relative path: C: \Java\ jdk1.8bin, jdk1.8 is the reference path. C :\ Java is unique to the parent path (last quarter folder) of the reference path. Bin is the subpath of the reference path (the folder at the next level). Multiple File(File parent,String Child)e(File parent,String Child). Parent is the parent path of the File type, and child is a String of subpaths

public static void main(String[ ] args) { method( ); method_2(); method_3(); } /* *File class construct, pass string argument (path) */ public static voidmethod() {// C: \Java\jdk1.8.0_ 221\bin File File = new File()"C: \ \ Java \ \ 221 \ \ bin jdk1.8.0 _"); System.out.println(file); } /* *File class constructor, passing the parent path of the string and the child path of the string */ public static voidmethod_2() {
	File file = new File("C:\\Java"."Jdk1.8.0 _221"); System.out.println(file); } /* *File class constructor, passing the parent path of type File and the child path of string */ public static voidmethod_3(){
	File parent = new File("C:\\Java");
	File file = new File(parent, "Jdk1.8.0 _ _221");
	System.out.println(file);
}
Copy the code

A static member variable of the File class

Static String separator the system’s default name separator static String pathSeparator the system’s pathSeparator. End of a path

Creation of the File class

Boolean createNewFile() Creates a new File, returns true on success, File path and File name, in the constructor of File. If the file already exists, it will not be created, return false

public static void main(String[] args) throws IOException { method( ) ; method_2( ); } /* *File class method createNewFile() creates a File */ public static void method() throws IOException {File File = new File("d:\\abc.txt"); boolean b = file. createNewFile( ); System. out. println(b); } /* *File class method,mkdirs() create folder */ public static voidmethod_2( ) {
	File file =new File("d:\\abc");
	boolean b =file . mkdirs();
	System. out. println(b);
}
Copy the code

Delete method of the File class

Boolean delete() Deletes a file

public static void main(String[] args) throws IOException {
	method_ 3( );
}
public static void method_ 3( ) {
	File file = new File("d:\\1. txt");
	boolean b=file.delete();
	System. out. println(b);
}
Copy the code

File class judgment method

Boolean exists() checks whether the path in the File constructor really exists. Returns true if it does. Boolean isDirectory() checks whether the path in the File constructor is a directory. Boolean isFile() Checks whether the path in the File constructor is a File or not

public Istatic void main(String[] args) { method( ); method_2( ); } /* *File class method to check whether exists() */ public static voidmethod( ) {
	File file = new File("d:\\springboot_ initializr.jar"); boolean b=file.exists(); System. out. println(b); } /* *File */ isDirectory() isFile() */ public static voidmethod_2( ) {
	File file = new File("d:\\driver");
	if(file.exists()) { boolean b = file. isDirectory(); System. out . println(b); b = file. isFile(); System. out . println(b); }}Copy the code

Get the File class

String getName() returns the name of the path in the File constructor, possibly the File name, String getPath() returns the String form of the path name. File getAbsoluteFile() returns the absolute path of the path. The return value is the File object. The return value is a File object

public static void main(String[] args) { method( ); method_2(); method_3(); method_4(); } public static void getName(); public static void getName()method( ) {
	File file = new File("C: \ \ Java \ \ jdk1.8.0 _221 \ \ bin");
	String name = file. getName( );
	System. out . println(name) ;
	file = new File("C: \ \ Java \ \ jdk1.8.0 _221 \ \ bin \ \ javac exe"); String name = file. getName( ); System. out . println(name) ; } public static void getPath() public static void getPath() public static void getPath(method_2() {
	File file = new File("C: \ \ Java \ \ jdk1.8.0 _ 221"."bin"); String path = file. getPath(); System. out . println(path) ; } /* * getAbsoluteFile() getsoluteFile () getsoluteFile () getsoluteFile () getsoluteFile () getsoluteFile () getsoluteFilemethod_3() {
	File file = new File("bin"); File absoluteFile =_ file. getAbsoluteFile(); System. out . println(absoluteFile) ; } public static void getParentFile(); public static void getParentFile(method_4() {
	File file = new File("C: \ \ Java \ \ 221 \ \ bin jdk1.8.0 _"); File parentFile = file.getparentFile (); System. out. println(parentFile); parentFile = file. getParentFile(); System. out. println(parentFile); }Copy the code

The list starting method of the File class

File[] listFiles() gets a list of all files (folders) in the constructor’s path. Static File[] listRoots() gets all the root directories in the current computer system

public static void main(String[] args) { method(); method_2(); method_3(); } /* *File class method,length() the number of bytes */ public static voidmethod() {
	File file = new File("C: \ \ Java \ 221 \ \ SRC \ jdk1.8.0 _ zip"); long length = file.length(); System. out. println(length); } /* *File class method, listFiles() traverses the folder */ public static voidmethod_2() {
	File file = new File("C: \ \ Java \ \ jdk1.8.0 _ 221");
	File[] files = file.listFiles( );
	for(File f : files) { System. out . println(f) ; }} /* * File method,listRoots(() static */ public static voidmethod_3() {
	File[] files=File.listRoots();
	for(File f:files) { System.out.println(f); }}Copy the code

File filter

The listFiles() method of the File class gets files under the ABC directory. Only.java files. Other types of files are not retrieved

Java.io.FileFilter interface, FileFilter interface, to filter the obtained files. The implementation class for this interface can be passed to the method listFiles(). Boolean Accept (File f) Custom implementation class File[] listFiles(FileFilter filter) Interface for passing File filters

public static void main(String[] args) {
	File file = new File("d:/abc"); File[] files = file.listFiles(new MyFilter());for(File f : files) { System. out . println(f); }}Copy the code
Class MyFilter implements FileFilter{public Boolean Accept (File pathname) {MyFilter implements FileFilter{public Boolean Accept (File pathname) { Javal String Class method endsWith ignores casereturn pathname . getName( ). toLowerCase() .endsWith(" . java"); }}Copy the code

Directory traversal

If a subdirectory is found while iterating through a directory, the traversal method continues to call its own traversal

public static void main(String[ ] args) {
	iteratorDir(new File("d:/abc")); } public static void iteratorDir(File dir) {system.out.println (dir);} public static void iteratorDir(File dir) {system.out.println (dir); File[] files = dir.listfiles ();for(File f: files) {// determine if f is a directoryif(f. isDirectory()) {// continue iteratorDir() is to receive the directory, iteratorDir // define the same code method, not necessary, call my own iteratorDir(f); }else{ System . out . println(f); }}}Copy the code

IO stream objects

I: Input O: Output Flow Object: data flow from one device to another Example: A document flows from a hard disk to the memory. A document flows from the memory to a hard disk. A document flows from a hard disk to a mobile disk. It can flow from one machine to another

Everything is in bytes

Any data, in the form of a file, are bytes (text, pictures, music, games), Internet transfers, downloaded files, web disks

I/O flow classification

According to the flow of data. Input stream Input. The Output stream Output is classified according to the data type of the operation. Byte stream A byte stream can operate on any type of data. ■ what is text-type data: merges of categories that can be read directly using text tools (notepad, Notepad++, EdiPlus) opened. Byte OutputStream ■ the top-level abstract parent: java.io.OutputStream. Byte Inputstream ■ the top-level abstract base class: java.io. Inputstream. Character output stream ■ The top-level abstract base class: java.i0.writer. Character input stream ■ The top-level abstract base class: java.io. Reader

Byte output stream

Can operate any type of data, from the Java program, Output Output, also known as writing OutStream class method: are writing data method write

Void write(int b) Write a single byte void Write (byte[] b) write a byte array void Write (byte[] b,int off,int len) Write part of the byte array, start index, number of writes close() Close this stream, Release resources

A subclass of OutputStream

I/O stream object names are very readable prefix + suffix Prefix: what time period this stream can do suffix: which subclass this stream belongs to FileOutputStream:

Constructor. FileOutputStream(String Name) Specifies the name of the file passing the String (data destination). FileOutputStream(File File) Passes a File IO stream object of File type. The write method does not implement the write function. It calls the function of the operating system to implement the write and release the operating system resources

/* *I0 stream, data written to file * byte output stream subclass File0utputStream * Common steps for using stream objects: */ public static void main(String[] args) throws IOException{method(); public static void main(String[] args) throws IOException{method(); method_2(); method_3(); } /* *File0utputStream writes a single byte */ public static void method() throws IOException {// Create a stream object, constructor binding data destination FileOutputStream fos  = new FileOutputStream("d:/1.txt"); // Stream object method write write data fos.write (100); Fos.close (); } /* *File0utpdtStream writes a byte array */ public static void method_2() throws IOException{// Create a stream object, constructor binding data destination File0utputStream fos = new File0utputStream("d:/1. txt"); // Create a byte array byte[] bytes=" abcdefg".getBytes(); // Byte stream, write the byte array fos.write (bytes); Fos.close (); } public static void method_3() throws IOException{File0utputStream fos = new File0utputStream"d:/1. txt"); // Create a byte array byte[] bytes=" abcdefg".getBytes(); // start index, number of writes fos.write (bytes,3,2); Fos.close (); }Copy the code

Appending files and line feeds

Fileoutputstream(String name, Boolean append) Fileoutputstream(String name, Boolean append) Pass the second argument true, append to write to newline, use newline character \r\n

public static void main(String[] args) throws IOException{ method_4(); method_5(); */ public static void method_4() throws IOException {FileOutputStream fos = new FileOutputStream("d:/a. txt" , true); fos . write(122); fos. close(); } /* *File0utputStream appends to the end of the previous line, *\r\n */ public static void IOException {FileOutputStream fos = new FileOutputStream("d:/a. txt");
	fos . write(" abc\r\n" . getBytes());
	fos . write(" xyz" . getBytes());
	fos.close();
}
Copy the code
/* *I0 stream object exception handling: standard writing * resource release, write in finally, regardless of whether the file was successfully written, the resource must be released *try defined variables, Public static void main(String[] args) {FileOutputStream fos = nu11; //File0utputStream fos1 = null; try { fos = new File0utputStream("a. txt");
		//fos1 = new FileOutputStream("a1 . txt");
		fos . write(97);
	}catch( IOException ex) {
		ex. printStackTrace( );
	}finally{
		if(fos! =null) try { fos.close(); }catch( IOException ex) { ex.printStackTrace();
		}
		/*
		* try { fos1. close(); }catch(IOException ex) { ex. printStackTrace(); 
		*/
	}
	name();
}
public static void name() {
	try (File0utputStream fos = new File0utputStream( "b:/a.txt"); File0utputStream fos2 = new File0utputStream(""){
	fos . write(97);
	}catch( IOException ex) {
	ex. printStackTrace( ); }}Copy the code

Byte input stream

It can operate on any type of data and read data from other devices into methods of the AVA InputStream class: both read methods

Int read() reads a single byte, returns the bytes read, and returns -1 when it reaches the end of the stream. Int read(byte[] b) reads the bytes, stores them in an array, and returns -1 when it reaches the end of the stream. Close () closes the stream and frees the resource

A subclass of InputStream

Subclasses FileInputStream:

Constructor. FileInputStream(String Name) The file name (data source) that passes the String. FileInputStream(File File) Transmits files of type File

/* * bytes input stream, FileInputStream reads file * reads a single byte methodread() */ public static void main(String[] args)throws IOException{// Create a byte input stream object FileInputStream("a.txt"); // Read a single byte methodread()
	int i = fis.read();
	fis. close();
}
Copy the code
Public static void main(String[] args)throws IOException{// Create a byte input stream object. In the constructor, bind the data source file FileInputStream fis = new FileInputStream("a. txt"); // Read a single byte methodread(a) / /readInt I = 0; / / receiveread() method's return valuewhile( (i = fis.read())! =-1 ) { System.out.print((char)i) } fis. close(); }Copy the code
/* * bytes input stream, FileInputStream reads file * reads byte array methodread(byte[] b) */ public static void main(String[] args) throws IOException{// Create a byte input stream object and bind the data source FileInputStream fis = new FileInputStream("a.txt"); Byte [] bytes = new byte[2]; int i = fis.read(bytes); System. out. println(i); System. out . println(new String(bytes)) ; fis.close(); }Copy the code
Public static void main(String[] args) throws IOException{// Create a byte input stream object and bind the data source FileInputStream fis = new FileInputStream("a. txt"); The recommended length is 1024 integer times 1KB byte[] bytes = new byte[1024]; int i =0; / / receivereadThe () method returns the valuewhile ( (i = fis. read(bytes)) ! /* * new String(byte[] b, start index, turn several) */ system.out.print(new String(bytes ,0,i));
	}
	fis. close();
}
Copy the code

Problem with byte input stream reading Chinese

Byte input stream, read Chinese characters (unreadable)

*/ public static void main(String[] args) throws IOException{FileInputStream fis = new FileInputStream("b. txt");
	byte[] bytes = new byte[1024];
	int i=0;
	while( (i = fis.read(bytes)) ! =-1) { System. out .print(new String(bytes,0,i));
	}
	fis. close();
}
Copy the code

Byte stream: File assignment copy

Data source: D :/ SpringBOOt_Initializr.jar Data destination: e: / Springboot_InitialZr.jar

Read a byte, write a byte read a byte array, write a byte array

pub1t.c static void main(String[] args) { copy_1(); copy_2(); } /* * Copy a file: Reads and writes a single byte */ public static void copy_1() throws IOException{// The byte input stream is bound to the data source FileInputStream fis = new FileInputStream(" d:/springboot_initializr . jar"); File0utputStream fos = new File0utputStream(" e:/springboot_initializr.jar"); Int I =0;while( (i = fis.read()) ! =-1) { fos . write(i); } fos. close(); fis.close() ; */ public static void copy_2() throws IOException{// Bind the byte input stream to the data source FileInputStream fis = new FileInputStream(" d:/springboot_initializr . jar"); File0utputStream fos = new File0utputStream(" e:/springboot_initializr.jar"); //fis reads a byte array, fos writes a byte array byte[] bytes = new byte[1024]; int i =0;while( (i = fis.read(bytes)) ! =-1) { fos . write(bytes,0,i); } fos. close(); fis.close() ; }Copy the code

The last

Thank you for reading here, after reading what do not understand, you can ask me in the comments section, if you think the article is helpful to you, remember to give me a thumbs up, every day we will share Java related technical articles or industry information, welcome to pay attention to and forward the article!