Use of File class
java.io.File class: the abstract representation of file and file directory path, which is platform independent
File can create, delete and rename files and directories, but file cannot access the file content itself.
If you need to access the file content itself, you need to use input / output streams.
To represent a real File or directory in a Java program, you must have a File pair
Like, but a File object in a Java program may not have a real File or directory.
The File object can be passed as a parameter to the constructor of the stream
Use of File class: common constructors
public File(String pathname) with pathname Create for path File Object, which can be an absolute path or a relative path, if pathname If it is a relative path, the default current path is in the system property user.dir Stored in. Absolute path: is a fixed path,Start with drive letter Relative path: it starts from a certain position public File(String parent,String child) with parent As the parent path, child Create for subpath File Object. public File(File parent,String child) According to a parent File Object and sub file path creation File object
Use of File class: path separator
Each level of directories in the path is separated by a path separator.
The path separator is system dependent:
windows and DOS systems use "\" by default
UNIX and URL s are represented by "/"
Java programs support cross platform operation, so the path separator should be used with caution.
To solve this problem, the File class provides a constant:
public static final String separator. Provide separators dynamically according to the operating system.
give an example:
File file1 = new File("d:\\atguigu\\info.txt"); File file2 = new File("d:" + File.separator + "atguigu" + File.separator + "info.txt"); File file3 = new File("d:/atguigu");
Use of File class: common methods
Get function of File class
public String getAbsolutePath(): Get absolute path public String getPath() : Get path public String getName() : Get name public String getParent(): Get the directory path of the upper level file. If not, return null public long length() : Gets the length of the file (that is, the number of bytes). Cannot get the length of the directory. public long lastModified() : Gets the last modification time, in milliseconds public String[] list() : Gets the name array of all files or file directories in the specified directory public File[] listFiles() : Gets the of all files or file directories in the specified directory File array File Rename function of class public boolean renameTo(File dest):Rename the file to the specified file path File Class judgment function public boolean isDirectory(): Determine whether it is a file directory public boolean isFile() : Determine whether it is a file public boolean exists() : Judge whether it exists public boolean canRead() : Judge whether it is readable public boolean canWrite() : Judge whether it is writable public boolean isHidden() : Determine whether to hide
Creation function of File class
public boolean createNewFile() : Create a file. If the file exists, it will not be created and will be returned false public boolean mkdir() : Create a file directory. If this file directory exists, it will not be created. If the upper directory of this file directory does not exist, it will not be created. public boolean mkdirs() : Create a file directory. If the upper file directory does not exist, create it together Note: if you create a file or the file directory does not have a write letter path, it is in the project by default Under the path.
Delete function of File class
public boolean delete(): Delete files or folders
Precautions for deletion:
Delete in Java does not go to the recycle bin.
To delete a file directory, please note that the file directory cannot contain files or file directories
Java IO principle
I/O is the abbreviation of Input/Output. I/O technology is a very practical technology for
Data transmission between processing devices. Such as reading / writing files, network communication, etc.
In Java program, the input / output operation of data is in the form of "stream"
Method.
java. Various "stream" classes and interfaces are provided under the IO package to obtain different kinds of data
Data, and input or output data through standard methods
Classification of flow
According to different operation data units, it is divided into byte stream (8 bit) and character stream (16 bit)
According to the flow direction of data flow, it is divided into input flow and output flow
According to the different roles of flow, it can be divided into node flow and processing flow
- Java's IO stream involves more than 40 classes, which are actually very regular, all from the following four
Derived from an abstract base class. - The names of subclasses derived from these four classes are suffixed with their parent class names
IO stream system
Node flow: read and write data directly from the data source or destination
Processing flow: not directly connected to the data source or destination, but "connected" in the existing database
On top of the flow (node flow or processing flow), the program is provided through the processing of data
For more powerful reading and writing functions
InputStream & Reader InputStream and Reader Is the base class for all input streams. InputStream(Typical implementation: FileInputStream) int read() int read(byte[] b) int read(byte[] b, int off, int len) Reader(Typical implementation: FileReader) int read() int read(char [] c) int read(char [] c, int off, int len)
The file IO resource opened in the program does not belong to the resource in memory, and the garbage collection mechanism cannot recover the resource
Source, so file IO resources should be explicitly closed.
FileInputStream gets input bytes from a file in the file system. FileInputStream
Used to read raw byte streams such as non text data. To read the character stream, you need to use FileReader
InputStream
int read() Reads the next byte of data from the input stream. Returns a value in the range 0 to 255 int Byte value. If because If the end of the stream has been reached and no bytes are available, the value is returned -1. int read(byte[] b) The maximum number of entries from this input stream b.length A byte of data is read into one byte Array. If because If no bytes are available after reaching the end of the stream, the value is returned -1. Otherwise, the actual read is returned as an integer Number of bytes. int read(byte[] b, int off,int len) Put the input stream at most len Data bytes read in byte Array. Attempt to read len Bytes, but read Bytes may also be less than this value. Returns the number of bytes actually read as an integer. If the flow is located If there are no bytes available at the end of the file, the value is returned -1. public void close() throws IOException Close this input stream and release all system resources associated with it.
Reader
int read() Read a single character. Characters read as integers, ranging from 0 to 65535 (0x00-0xffff)(2 individual Byte Unicode Code), if the end of the stream has been reached, return -1 int read(char[] cbuf) Read characters into an array. Returns if the end of the stream has been reached -1. Otherwise, the number of characters read this time will be returned. int read(char[] cbuf,int off,int len) Read characters into a part of the array. Save to array cbuf From off Start storage at and read at most len Word Symbol. Returns if the end of the stream has been reached -1. Otherwise, the number of characters read this time will be returned. public void close() throws IOException Close this input stream and release all system resources associated with it.
OutputStream & Writer
OutputStream and Writer are also very similar:
void write(int b/int c); void write(byte[] b/char[] cbuf); void write(byte[] b/char[] buff, int off, int len); void flush(); void close(); You need to refresh before closing this stream Because the character stream directly takes the character as the operation unit, so Writer You can replace the character array with a string, Namely String Object as a parameter void write(String str); void write(String str, int off, int len); FileOutputStream Get the output bytes from a file in the file system. FileOutputStream Used to write out raw byte streams such as non text data. To write out a character stream, you need to use FileWriter
OutputStream
Writes the specified byte to this output stream. write The general convention is to write a byte to the output stream. To write The bytes entered are parameters b Eight low positions. b The 24 high bits of will be ignored. Write 0~255 Scope. void write(byte[] b) take b.length Bytes from the specified byte Array writes to this output stream. write(b) The conventional agreement is: should And call write(b, 0, b.length) The effect is exactly the same. void write(byte[] b,int off,int len) Will specify byte Offset from array off Started len Bytes are written to this output stream. public void flush()throws IOException Refresh this output stream and force all buffered output bytes to be written out. Call this method to indicate that these bytes should be set up That is, write their expected target. public void close() throws IOException Close this output stream and free all system resources associated with it
Writer
void write(int c) Write a single character. The character to be written is contained in the 16 low bits of the given integer value, and the 16 high bits are ignored. Namely Write between 0 and 65535 Unicode Code. void write(char[] cbuf) Write character array. void write(char[] cbuf,int off,int len) Writes a part of a character array. from off Start, write len Characters void write(String str) Write string. void write(String str,int off,int len) Write a part of a string. void flush() Flush the buffer of the stream, then write them to the expected destination immediately. public void close() throws IOException Close this output stream and release all system resources associated with it.
read file
1. Create a stream object and load an existing file into the stream.
FileReader fr = new FileReader(new File("Test.txt"));
2. Create an array to store data temporarily.
char[] ch = new char[1024];
3. Call the read method of the stream object to read the data in the stream into the array.
fr.read(ch);
4. Close resources.
fr.close();
FileReader fr = null; try { fr = new FileReader(new File("c:\\test.txt")); char[] buf = new char[1024]; int len; while ((len = fr.read(buf)) != -1) { System.out.print(new String(buf, 0, len)); } } catch (IOException e) { System.out.println("read-Exception :" + e.getMessage()); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { System.out.println("close-Exception :" + e.getMessage()); } } }
write file
1. Create a stream object and create a data storage file
FileWriter fw = new FileWriter(new File("Test.txt"));
2. Call the write method of the stream object to write the data to the stream
fw.write("atguigu-songhongkang");
3. Close the stream resource and empty the data in the stream into the file.
fw.close();
FileWriter fw = null; try { fw = new FileWriter(new File("Test.txt")); fw.write("atguigu-songhongkang"); } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) try { fw.close(); } catch (IOException e) { e.printStackTrace(); } }
Attention
When defining the file path, note that "/" or "\" can be used.
When writing a file, if the constructor FileOutputStream(file) is used, there is a file with the same name in the directory
Pieces will be overwritten.
If the constructor FileOutputStream(file,true) is used, the file with the same name in the directory will not be overwritten,
Add content at the end of the file.
When reading a file, you must ensure that the file already exists, otherwise an exception will be reported.
Byte stream operation bytes, such as: mp3,. avi,. rmvb,mp4,. jpg,. doc,. ppt
Character stream can only operate on ordinary text files. The most common text
Piece: txt,. java,. c,. cpp and other language source code. Pay special attention Doc, Excel and PPT are not documents
This document
One of the processing streams: buffer stream
In order to improve the speed of data reading and writing, the Java API provides stream classes with buffering function, which are used in
When, an internal buffer array will be created, and 8192 bytes (8Kb) buffer will be used by default.
The buffer flow should be "nested" on the corresponding node flow. According to the data operation unit, the buffer flow can be divided into:
BufferedInputStream and BufferedOutputStream
BufferedReader and BufferedWriter
When reading data, the data is read into the buffer by block, and subsequent read operations directly access the buffer
When using BufferedInputStream to read byte files, BufferedInputStream will read byte files from
8192 (8Kb) are read from the file and stored in the buffer until the buffer is full
Read the next 8192 byte array.
When writing bytes to the stream, they will not be directly written to the file. They will be written to the buffer first until the buffer is full,
BufferedOutputStream will write the data in the buffer to the file at one time. usage method
flush() can force all the contents of the buffer to be written to the output stream
The order in which the flow is closed is opposite to the order in which it is opened. Just turn off the outermost flow, and turn off the outermost flow
The inner node flow will be closed accordingly
Use of the flush() method: manually write the contents of the buffer to the file
If it is the close() method of the stream object with buffer, it will not only close the stream, but also brush before closing the stream
The new buffer cannot be written out after it is closed
BufferedReader br = null; BufferedWriter bw = null; try { // Create a buffer stream object: it is a processing stream and a wrapper for a node stream br = new BufferedReader(new FileReader("d:\\IOTest\\source.txt")); bw = new BufferedWriter(new FileWriter("d:\\IOTest\\dest.txt")); String str; while ((str = br.readLine()) != null) { // Read one line of characters in a character text file at a time bw.write(str); // Write one line of string at a time bw.newLine(); // Write in line separator } bw.flush(); // refresh buffer } catch (IOException e) { e.printStackTrace(); } finally { // Close IO stream object try { if (bw != null) { bw.close(); // When the filter flow is closed, it will automatically close the underlying node flow it wraps } } catch (IOException e) { e.printStackTrace(); } try { if (br != null) { br.close(); } } catch (IOException e) { e.printStackTrace(); } }
Processing flow 2: conversion flow
Conversion stream provides conversion between byte stream and character stream
The Java API provides two transformation streams:
InputStreamReader: convert InputStream to Reader
OutputStreamWriter: converts the Writer to OutputStream
When the data in the byte stream is all characters, the operation of converting to character stream is more efficient.
Many times, we use transform stream to deal with the problem of file scrambling. Implement coding and
Decoding function.
InputStreamReader
The input stream of bytes is converted into the input stream of characters according to the specified character set.
Need to "socket" with InputStream.
constructor
public InputStreamReader(InputStream in)
public InputSreamReader(InputStream in,String charsetName)
For example: Reader isr = new InputStreamReader(System.in, "gbk");
Specify character set
OutputStreamWriter
Realize the conversion of the output stream of characters into the output stream of bytes according to the specified character set.
Need to "socket" with OutputStream.
constructor
public OutputStreamWriter(OutputStream out)
public OutputSreamWriter(OutputStream out,String charsetName)
public void testMyInput() throws Exception { FileInputStream fis = new FileInputStream("dbcp.txt"); FileOutputStream fos = new FileOutputStream("dbcp5.txt"); InputStreamReader isr = new InputStreamReader(fis, "GBK"); OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK"); BufferedReader br = new BufferedReader(isr); BufferedWriter bw = new BufferedWriter(osw); String str = null; while ((str = br.readLine()) != null) { bw.write(str); bw.newLine(); bw.flush(); } bw.close(); br.close(); }
Supplementary: character coding
Origin of coding table
Computers can only recognize binary data, which originated from electrical signals in the early days. In order to facilitate the application of the computer, it can recognize
Don't write in different countries. The words of each country are expressed in numbers and correspond one by one to form a table.
This is the coding table.
Common coding table
ASCII: American standard information interchange code.
It can be represented by 7 bits of a byte.
ISO8859-1: Latin code table. European code table
Represented by 8 bits of a byte.
GB2312: Chinese coding table of China. Up to two bytes encode all characters
GBK: China's Chinese coding table has been upgraded to integrate more Chinese characters and symbols. Up to two byte encoding
Unicode: international standard code, which integrates all characters currently used by human beings. Assign a unique to each character
Character code. All text is represented by two bytes.
UTF-8: variable length encoding method. 1-4 bytes can be used to represent a character.
Processing stream 3: standard input and output streams (understand)
System.in and system Out represents the input and output devices of the system standard respectively
The default input device is keyboard, and the output device is display
System. The type of in is InputStream
System. The type of out is PrintStream, which is a subclass of OutputStream
Subclass of FilterOutputStream
Redirection: change the default device through the setIn and setOut methods of the System class.
public static void setIn(InputStream in)
public static void setOut(PrintStream out)
System.out.println("Please enter information(Exit input e or exit):"); // Wrap the byte stream of "standard" input stream (keyboard input) into character stream and then into buffer stream BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = null; try { while ((s = br.readLine()) != null) { // Read a line of data entered by the user -- > blocking program if ("e".equalsIgnoreCase(s) || "exit".equalsIgnoreCase(s)) { System.out.println("Safe exit!!"); break; } // Convert the read whole line of string to uppercase output System.out.println("-->:" + s.toUpperCase()); System.out.println("Continue entering information"); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); // When the filter flow is closed, the underlying node flow it wraps is automatically closed } } catch (IOException e) { e.printStackTrace(); } }
Processing stream 4: print stream (understand)
Realize the conversion of the data format of the basic data type into string output
Print streams: PrintStream and PrintWriter
Provides a series of overloaded print() and println() methods for output of multiple data types
The output of PrintStream and PrintWriter will not throw IOException
PrintStream and PrintWriter have automatic flush function
All characters printed by PrintStream are converted to bytes using the platform's default character encoding.
When you need to write characters instead of bytes, you should use the PrintWriter class.
System.out returns an instance of PrintStream
PrintStream ps = null; try { FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt")); // Create a printout stream and set it to automatic refresh mode (the output buffer will be refreshed when writing newline character or byte '\ n') ps = new PrintStream(fos, true); if (ps != null) {// Change standard output stream (console output) to file System.setOut(ps); } for (int i = 0; i <= 255; i++) { // Output ASCII characters System.out.print((char) i); if (i % 50 == 0) { // One row for every 50 data System.out.println(); // Line feed } } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (ps != null) { ps.close(); } }
Processing flow 5: data flow (understanding)
In order to easily operate the basic data types of Java language and String data, you can use data flow.
Data flow has two classes: (used to read and write data of basic data type and String class)
DataInputStream and DataOutputStream
"Socket" on the streams of subclasses InputStream and OutputStream respectively
Methods in DataInputStream
boolean readBoolean()
byte readByte()
char readChar()
float readFloat()
double readDouble()
short readShort()
long readLong()
int readInt()
String readUTF() void readFully(byte[] b)
Methods in DataOutputStream
Change the read of the above method to the corresponding write
DataOutputStream dos = null; try { // Creates a data output stream object connected to the specified file dos = new DataOutputStream(new FileOutputStream("destData.dat")); dos.writeUTF("I Love Beijing Tiananmen "); // Write UTF string dos.writeBoolean(false); // Write Boolean dos.writeLong(1234567890L); // Write long integer System.out.println("Write file succeeded!"); } catch (IOException e) { e.printStackTrace(); } finally { // Close flow object try { if (dos != null) { // When the filter flow is closed, the underlying node flow it wraps is automatically closed dos.close(); } } catch (IOException e) { e.printStackTrace(); } }
DataInputStream dis = null; try { dis = new DataInputStream(new FileInputStream("destData.dat")); String info = dis.readUTF(); boolean flag = dis.readBoolean(); long time = dis.readLong(); System.out.println(info); System.out.println(flag); System.out.println(time); } catch (Exception e) { e.printStackTrace(); } finally { if (dis != null) { try { dis.close(); } catch (IOException e) { e.printStackTrace(); } } }
Processing flow 6: object flow
ObjectInputStream and ojbectoutputstream
A processing stream used to store and read basic data type data or objects. Its strength is that it can
To write the objects in Java to the data source and restore the objects from the data source.
Serialization: a mechanism for saving basic type data or objects with ObjectOutputStream class
Deserialization: a mechanism for reading basic type data or objects with the ObjectInputStream class
ObjectOutputStream and ObjectInputStream cannot serialize static and transient data
Member variable of decoration
object serialization
The object serialization mechanism allows Java objects in memory to be converted into platform independent binary streams from
This binary stream is allowed to be permanently stored on disk or circulated through the network
Input to another network node// When other programs get this binary stream, they can restore it to the original
Java object from
The advantage of serialization is that it can convert any object that implements the Serializable interface into byte data,
So that it can be restored when saving and transferring
The parameters of the remote invoke method and the remote invoke method are
All return values must be implemented, and RMI is the basis of Java EE. Therefore, the serialization mechanism is
Foundation of Java EE platform
If you need to make an object support serialization mechanism, you must make the class to which the object belongs and its properties editable
Serialization. In order for a class to be serializable, the class must implement one of the following two interfaces.
Otherwise, a NotSerializableException is thrown
Serializable
Externalizable
All classes that implement the Serializable interface have a static variable that represents the serialized version identifier:
private static final long serialVersionUID;
serialVersionUID is used to indicate the compatibility between different versions of a class. In short, the goal is to serialize objects
For version control, check whether each version is compatible during deserialization.
If the class does not show the definition of this static constant, its value is self defined by the Java runtime environment according to the internal details of the class
Generated by motion. If the instance variable of the class is modified, the serialVersionUID may change. Therefore, it is suggested that,
Explicit declaration.
In short, the serialization mechanism of Java is verified by judging the serialVersionUID of the class at run time
Certificate of version consistency. During deserialization, the JVM will send the data in the transmitted byte stream
The serialVersionUID is compared with the serialVersionUID of the corresponding local entity class. If it is the same
It is considered to be consistent and can be deserialized, otherwise there will be different serialization versions
Often. (InvalidCastException)
Serialize objects using object streams
If a class implements the Serializable interface, the object of the class is Serializable:
Create an ObjectOutputStream
Call the writeobject method of the ObjectOutputStream object to output the serializable object
Note that write once and operate flush() once
Deserialization
Create an ObjectInputStream
Call the readObject() method to read the object in the stream
Emphasize: if the attribute of a class is not a basic data type or String type, but another
Reference type, then the reference type must be serializable, otherwise it has the
Field's class cannot be serialized
//Serialization: writing objects to disk or network transmission. //Requires that the object must be serialized ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.txt")); Person p = new Person("Mei Mei Han", 18, "Zhonghua Street", new Pet()); oos.writeObject(p); oos.flush(); oos.close(); //Deserialization: read out the object data source in the disk. ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.txt")); Person p1 = (Person)ois.readObject(); System.out.println(p1.toString()); ois.close();
Talk about your understanding of Java io. Serializable interface. We know it is used for serialization. It is an empty method interface. Is there any other understanding?
Objects that implement the Serializable interface can be converted into a series of bytes and can be used later
Completely return to the original appearance. This process can also be carried out through the network. This means that the serializer
The braking system can automatically compensate for the differences between operating systems. In other words, it can be created on the Windows machine first
Build an object, serialize it, send it to a Unix machine through the network, and then there
Reassemble accurately. You don't have to care about how the data is represented on different machines, and you don't have to
Care about byte order or any other details.
Because most classes as parameters, such as String and Integer, are implemented
java.io.Serializable interfaces can also take advantage of the polymorphic nature as parameters to make the interface more flexible
Flexibility.
Random access file stream
RandomAccessFile class
RandomAccessFile is declared in Java IO package, but directly inherited from Java Lang.Object class. and
And it implements two interfaces: DataInput and DataOutput, which means that this class can read and output
You can write.
RandomAccessFile class supports "random access", and the program can directly jump to any part of the file
Place to read and write documents
Only partial contents of the file can be accessed
You can append content to an existing file
The RandomAccessFile object contains a record pointer to indicate the location of the current read / write location.
RandomAccessFile class object can move the record pointer freely:
long getFilePointer(): get the current position of the file record pointer
void seek(long pos): position the file record pointer to the pos position
constructor
public RandomAccessFile(File file, String mode)
public RandomAccessFile(String name, String mode)
To create an instance of RandomAccessFile class, you need to specify a mode parameter, which refers to
Set the access mode of RandomAccessFile:
r: Open as read-only
rw: open for reading and writing
rwd: open for reading and writing; Synchronize file content updates
rws: open for reading and writing; Synchronize file content and metadata updates
If the mode is read-only r. Instead of creating a file, it will read an existing file,
If the read file does not exist, an exception occurs. If the mode is rw read / write. If the file does not
If it exists, the file will be created. If it exists, it will not be created
Read file contents
RandomAccessFile raf = new RandomAccessFile("test.txt", "rw"); raf.seek(5); byte [] b = new byte[1024]; int off = 0; int len = 5; raf.read(b, off, len); String str = new String(b, 0, len); System.out.println(str); raf.close();
Write file contents
RandomAccessFile raf = new RandomAccessFile("test.txt", "rw"); raf.seek(5); //Read it first String temp = raf.readLine(); raf.seek(5); raf.write("xyz".getBytes()); raf.write(temp.getBytes()); raf.close();
Basic application of flow
Streams are used to process data.
When processing data, you must first clarify the data source and data destination
The data source can be a file or a keyboard.
The data destination can be a file, display or other device.
The stream is only used to facilitate data transmission and process the transmitted data, such as filtering
Conversion processing, etc
Java NIO overview
Java NIO (New IO, non blocking IO) is a new set introduced from Java version 1.4
IO API, which can replace the standard Java IO API. NIO has the same function and purpose as the original io
NIO supports buffer oriented (IO is stream oriented) and stream based
IO operation of channel. NIO will read and write files in a more efficient way.
The Java API provides two sets of NIO, one for standard input and output NIO and the other for net
Network programming NIO.
|-----java.nio.channels.Channel
|-----FileChannel: processing local files
|-----SocketChannel: the Channel of TCP network programming client
|-----Serversocketchannel: the server-side Channel of TCP network programming
|-----Datagram Channel: the Channel of the sender and receiver in UDP network programming
NIO. 2
With the release of JDK 7, Java has greatly extended NIO and enhanced the
File processing and file system feature support, so that we call them NiO 2.
Because of some functions provided by NIO, NIO has become more and more important in file processing
Part of
Path, Paths, and Files core API s
Early Java only provided a File class to access the File system, but the function of File class is relatively limited
The performance of the method provided is also not high. Moreover, most methods only return failure when there is an error, and do not provide exception
Constant information.
NIO. In order to make up for this deficiency, the Path interface is introduced to represent a platform independent platform Path
Describes the location of files in the directory structure. Path can be regarded as an upgraded version of the File class, which actually refers to the data
The source may not exist.
In the past, IO operations were written like this:
import java.io.File;
File file = new File("index.html");
But in Java 7, we can write this:
import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get("index.html");
Meanwhile, NiO 2 in Java nio. Files and Paths tool classes are also provided under the file package. Files contains
A large number of static tools and methods are used to operate files; Path s contains two static Paths that return Paths
Factory method.
The static get() method provided by the Paths class is used to obtain the Path object:
static Path get(String first, String... more): used to string multiple characters into a path
Static Path get (uri): returns the Path corresponding to the specified uri
Path interface
Path common methods:
String toString(): returns the string representation of the calling Path object
boolean startsWith(String path): judge whether to start with path path
boolean endsWith(String path): judge whether to end with path path
boolean isAbsolute(): judge whether it is an absolute path
Path getParent(): the returned path object contains the entire path, not the file path specified by the path object
Path getRoot(): returns the root path of the calling path object
Path getFileName(): returns the file name associated with the calling path object
int getNameCount(): returns the number of elements behind the Path root directory
Path getName(int idx): returns the path name of the specified index location idx
Path toAbsolutePath(): returns the calling path object as an absolute path
Path resolve(Path p): merge two paths and return the path object corresponding to the merged path
File toFile(): converts Path to an object of file class
Files class
java.nio.file.Files is a tool class used to manipulate files or directories.
Files common methods:
Path copy(Path src, Path dest, CopyOption... how): copy of files
Path createdirectory (path, fileattribute <? >... attr): create a directory
Path CreateFile (path, fileattribute <? >... arr): create a file
Void delete (path): delete a file / directory. If it does not exist, an error will be reported
Void deleteifexists (path): delete the file / directory corresponding to the path if it exists
Path move(Path src, Path dest, CopyOption... how): move src to dest
Long size (path): returns the size of the specified file
Files common method: used to judge
Boolean exists (path, linkoption... opts): judge whether the file exists
Boolean isdirectory (path, linkoption... opts): judge whether it is a directory
Boolean isregularfile (path, linkoption... opts): judge whether it is a file
Boolean ishidden (path): judge whether it is a hidden file
Boolean is readable (path): judge whether the file is readable
Boolean iswritable (path): judge whether the file is writable
Boolean notexists (path, linkoption... opts): judge whether the file does not exist
Files common method: used to operate content
Seekablebytechannel newbytechannel (path, openoption... how): get the connection with the specified file
Next, how specifies the opening method.
DirectoryStream
Newdirectorystream (path): open the directory specified in path
InputStream newinputstream (path, openoption... how): get the InputStream object
OutputStream newoutputstream (path, openoption... how): get the OutputStream object