In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "the understanding and use of Java File class". In daily operation, I believe many people have doubts about the understanding and use of Java File class. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "understanding and use of Java File class". Next, please follow the editor to study!
1. The use of File class 1. Understanding of File class
An object of the File class that represents a file or a file directory (commonly known as a folder).
The File class is declared under the java.io package: an abstract representation of files and file paths, regardless of platform.
The File class deals with the creation, deletion, renaming, modification time, file size and other methods of a file or file directory, but not the operation of writing or reading the contents of a file. If you need to read or write the contents of a file, you must use an IO stream to do so.
To represent a real file or directory in a Java program, you must have a File object, but a File object in a Java program may not have a real file or directory.
Objects of subsequent File classes are often passed as parameters to the stream's constructor, indicating the "end point" of reading or writing.
2. Instantiation of File 2.1 Common constructors
File (String filePath)
File (String parentPath,String childPath)
File (File parentFile,String childPath)
Code example:
@ Testpublic void test1 () {/ / Constructor 1 File file1 = new File ("hello.txt"); File file2 = new File ("E:\ workspace_idea\\ JavaSenic\\ IO\\ hello.txt"); System.out.println (file1); System.out.println (file2); / / Constructor 2 File file3 = new File ("E:\ workspace_idea\ JavaSenior", "hello.txt"); System.out.println (file3) / / Constructor 3 File file4 = new File (file3, "hi.txt"); System.out.println (file4);} 2.2 path classification
Relative path: the path specified compared to a certain path.
Absolute path: the path to a file or file directory, including a drive letter.
Description:
In IDEA:
If you use the unit test method in JUnit, the relative path is under the current Module.
If you use the main () test, the relative path is under the current Project.
In Eclipse:
Whether you use the unit test method or the main () test, the relative path is under the current Project.
2.3 path separator
Windows and DOS systems use "\" by default to represent
UNIX and URL use "/" to represent
Java programs support cross-platform operation, so path delimiters should be used with caution.
To solve this problem, the File class provides a constant: public static final String separator. Provide delimiters dynamically, depending on the operating system.
For example:
/ / windows and DOS systems File file1 = new File ("E:\\ io\\ test.txt"); / / UNIX and URLFile file = new File ("E:/io/test.txt"); / / constant File file = new File provided by java ("E:" + File.separator+ "io" + File.separator+ "test.txt")
3. The common methods of File class 3.1 the acquisition function of File class
Public String getAbsolutePath (): get the absolute path
Public String getPath (): get the path
Public String getName (): get the name
Public String getParent (): gets the path to the upper file directory. If not, return null
Public long length (): gets the file length (that is, the number of bytes). Cannot get the length of the directory.
Public long lastModified (): get the last modification time, millisecond value
The following two methods apply to file directories:
Public String [] list (): gets an array of names of all files or file directories under the specified directory
Public File [] listFiles (): gets the File array of all files or file directories under the specified directory
Code example:
@ Testpublic void test2 () {File file1 = new File ("hello.txt"); File file2 = new File ("d:\\ io\\ hi.txt"); System.out.println (file1.getAbsolutePath ()); System.out.println (file1.getPath ()); System.out.println (file1.getName ()); System.out.println (file1.getParent ()); System.out.println (file1.length ()) System.out.println (new Date (file1.lastModified (); System.out.println (); System.out.println (file2.getAbsolutePath ()); System.out.println (file2.getPath ()); System.out.println (file2.getName ()); System.out.println (file2.getParent ()); System.out.println (file2.length ()); System.out.println (file2.lastModified ()) } @ Testpublic void test3 () {File file = new File ("D:\ workspace_idea1\\ JavaSenior"); String [] list = file.list (); for (String s: list) {System.out.println (s);} System.out.println (); File [] files = file.listFiles (); for (File f: files) {System.out.println (f);} 3.2 File class renaming function
Public boolean renameTo (File dest): renames the file to the specified file path
Note: file1.renameTo (file2) as an example: to ensure that true is returned, file1 is required to exist on the hard disk, and file2 cannot exist on the hard disk.
Code example:
@ Testpublic void test4 () {File file1 = new File ("hello.txt"); File file2 = new File ("D:\\ io\\ hi.txt"); boolean renameTo = file2.renameTo (file1); System.out.println (renameTo);} 3.3 judgment function of File class
Public boolean isDirectory (): determines whether it is a file directory
Public boolean isFile (): determines whether it is a file or not
Public boolean exists (): determine whether it exists
Public boolean canRead (): judge whether it is readable or not
Public boolean canWrite (): judge whether it is writable or not
Public boolean isHidden (): determine whether to hide or not
Code example:
@ Testpublic void test5 () {File file1 = new File ("hello.txt"); file1 = new File ("hello1.txt"); System.out.println (file1.isDirectory ()); System.out.println (file1.isFile ()); System.out.println (file1.exists ()); System.out.println (file1.canRead ()); System.out.println (file1.canWrite ()); System.out.println (file1.isHidden ()) System.out.println (); File file2 = new File ("d:\\ io"); file2 = new File ("d:\\ io1"); System.out.println (file2.isDirectory ()); System.out.println (file2.isFile ()); System.out.println (file2.exists ()); System.out.println (file2.canRead ()); System.out.println (file2.canWrite ()) System.out.println (file2.isHidden ());} 3.4 creation function of the Flie class
Create a corresponding file or file directory on the hard disk
Public boolean createNewFile (): create a file. If the file exists, it is not created and false is returned.
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 this file directory exists, it will not be created. If the upper file directory does not exist, create it at the same time
Code example:
@ Testpublic void test6 () throws IOException {File file1 = new File ("hi.txt"); if (! file1.exists ()) {/ / file creation file1.createNewFile (); System.out.println ("created successfully");} else {/ / file exists file1.delete (); System.out.println ("deleted successfully") } @ Testpublic void test7 () {/ / File directory creation File file1 = new File ("d:\ io\\ io1\\ io3"); boolean mkdir = file1.mkdir (); if (mkdir) {System.out.println ("created successfully 1");} File file2 = new File ("d:\ io\\ io1\\ io4"); boolean mkdir1 = file2.mkdirs () If (mkdir1) {System.out.println ("created successfully 2");} / / for deletion to succeed, there cannot be subdirectories or files File file3 = new File ("D:\ io\\ io1\\ io4") in the io4 file directory; file3 = new File ("D:\\ io\\ io1"); System.out.println (file3.delete ()); delete function of} 3.5 File class
Delete a file or file directory on disk
Public boolean delete (): delete a file or folder
Delete Note: the deletion in Java does not go to the Recycle Bin.
4. Memory parsing
5. A little exercise
Using Fie constructor, new a file directory file 1) create multiple files and directory 2) Writing method to delete the specified files in fle
@ Testpublic void test1 () throws IOException {File file = newFile ("E:\ io\\ io1\\ hello.txt"); / / create another file in the same directory as file, named: .txt File destFile = newFile (file.getParent (), ".txt"); boolean newFile = destFile.createNewFile (); if (newFile) {System.out.println ("created successfully!") ;}}
Determine whether there is a file with the suffix jpg in the specified directory, and if so, output the file name
Public class FindJPGFileTest {@ Test public void test1 () {File srcFile = new File ("d:\\ code"); String [] fileNames = srcFile.list (); for (String fileName: fileNames) {if (fileName.endsWith (".jpg")) {System.out.println (fileName) }} @ Test public void test2 () {File srcFile = new File ("d:\\ code"); File [] listFiles = srcFile.listFiles (); for (File file: listFiles) {if (file.getName (). EndsWith (".jpg")) {System.out.println (file.getAbsolutePath ()) The File class provides two file filter methods * public String [] list (FilenameFilter filter) * public File [] listFiles (FileFilter filter) * / @ Test public void test3 () {File srcFile = new File ("d:\\ code") File [] subFiles = srcFile.listFiles (new FilenameFilter () {@ Override public boolean accept (File dir, String name) {return name.endsWith (".jpg");}}); for (File file: subFiles) {System.out.println (file.getAbsolutePath ());}
Traverses all file names in the specified directory, including files in the subfile directory. Extension 1: and calculate the size of the space occupied by the specified directory extension 2: delete the specified file directory and all files under it
Public class ListFileTest {public static void main (String [] args) {/ / Recursive: file directory / * * prints the names of all files in the specified directory, including files in the subfile directory * / 1. Create the directory object File file = new File ("E:\\ test"); / / 2. Print subdirectory printSubFile (file);} / * Recursive method traverses files in all directories * * @ param dir * / public static void printSubFile (File dir) {/ / print subdirectory File [] files = dir.listFiles () For (File f: files) {if (f.isDirectory ()) {/ / if it is a file directory, recursively call its own printSubFile (f);} else {System.out.println (f.getAbsolutePath ()) / / output absolute path} / / extension 1: find the size of the space in the specified directory / / find the total size of any directory public long getDirectorySize (File file) {/ / file is a file, then directly return file.length () / / file is a directory Adding up all the sizes of its next level is its total size long size = 0 If (file.isFile ()) {size + = file.length ();} else {File [] allFiles = file.listFiles (); / / get the next level of file / / accumulate the size of all [I] for (File f: allFiles) {size + = getDirectorySize (f) / / the size of f}} return size } / * extension 2: delete the specified directory * / public void deleteDirectory (File file) {/ / if file is a file, directly delete / / if file is a directory, kill its next level first, and then delete your own if (file.isDirectory ()) {File [] allFiles = file.listFiles () / / Recursive call to delete file lower-level for (File f: allFiles) {deleteDirectory (f);}} else {/ / delete file file.delete ();} II. Overview of IO stream 1. Brief introduction
IO is an acronym for Input/Output, and IMab O technology is a very practical technology for dealing with data transfer between devices. Such as reading / writing files, network communications, etc.
In the Java program, the input and output operation of the data is carried out in a "stream" way.
Various "stream" classes and interfaces are provided under the Java.IO package to obtain different kinds of data and to input or output data through standard methods.
two。 Classification of streams
Operational data units: byte stream, character stream
For text files (.txt, .java, .c, .cpp), use character stream processing
For non-text files (.jpg, .mp3, .mp4, .avi, .doc, .ppt,...), use byte stream processing
Data flow direction: input stream, output stream
Input input: read external data (disk, CD, etc.) into the program (memory).
Output output: output program (memory) data to disk, CD and other storage devices.
The role of flow: node flow, processing flow
Node flow: read and write data directly from the data source or destination.
Processing flow: do not connect directly to the data source or destination, but "connect" on top of an existing stream (node flow or processing flow), providing the program with more powerful reading and writing capabilities through the processing of data.
The figure shows:
3. Systematic classification of IO flows 3.1 overall classification
The red box is the abstract base class and the blue box is the common IO stream.
InputStreamFileInputStream (read (byte [] buffer)) BufferedInputStream (read (byte [] buffer)) OutputSteamFileOutputStream (write (byte [] buffer,0,len) BufferedOutputStream (write (byte [] buffer,0,len) / flush () ReaderFileReader (read (char [] cbuf) BufferedReader (read (char [] cbuf) / readLine ()) WriterFileWriter (write (char [] cbuf,0)) Len) BufferedWriter (write (char [] cbuf,0,len) / flush () 3.3 description of abstract base class: abstract base class byte stream character stream input stream InputSteamReader output stream OutputSteamWriter
Note: Java's lO stream involves more than 40 classes, which are actually very regular and are derived from the following four abstract base classes.
Subclass names derived from these four classes are all suffixed with their parent class names.
3.3.1InputSteam & Reader
InputStream and Reader are the base classes for all input streams.
InputStream (typical implementation: FileInputStream)
Int read ()
Int read (byte [] b)
Int read (byte [] bmenint off,int len)
Reader (typical implementation: FileReader)
Int read ()
Int read (char [] c)
Int read (char [] c penint 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 recycle the resource, so the file IO resource should be explicitly closed.
FileInputStream gets input bytes from a file in the file system. FileInputStream is used to read raw byte streams such as non-text data. To read character streams, you need to use FileReader.
InputSteam:
Int read ()
Reads the next byte of data from the input stream. Returns int byte values in the range of 0 to 255. If no bytes are available because the end of the stream has been reached, a value of-1 is returned.
Int read (byte [] b)
Reads up to b.length bytes of data from this input stream into an byte array. If no bytes are available because the end of the stream has been reached, the value is-1. Otherwise, the number of bytes actually read is returned as an integer.
Int read (byte [] bmenint off,int len)
Reads up to len bytes of data in the input stream into the byte array. An attempt was made to read len bytes, but the bytes read may also be less than that value. Returns the number of bytes actually read as an integer. If no bytes are available because the stream is at the end of the file, a value of-1 is returned.
Public void close throws IOException
Close this input stream and release all system resources associated with the stream.
Reader:
Int read ()
Read a single character. Characters read as integers, ranging from 0 to 65535 (0x00-0xffff) (2-byte Unicode code), or-1 if the end of the stream has been reached.
Int read (char [] cbuf)
Reads characters into an array. Returns-1 if the end of the stream has been reached. Otherwise, the number of characters read this time is returned.
Int read (char [] cbuf,int off,int len)
Reads characters into some part of the array. Save it to the array cbuf, start at off, and read up to len characters. Returns-1 if the end of the stream has been reached. Otherwise, the number of characters read this time is returned.
Public void close throws IOException
Close this input stream and release all system resources associated with the stream
3.3.2 OutputSteam & 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 (); needs to be refreshed before closing the stream
Because character streams operate directly in characters, Writer can replace character arrays with strings, that is, taking String objects as parameters
Void write (String str)
Void write (String str,int off,int len)
FileOutputStream gets output bytes from a file in the file system. FileOutputstream is used to write out raw byte streams such as non-text data. To write out a character stream, you need to use FileWriter
OutputStream:
Void write (int b)
Writes the specified bytes to this output stream. The general protocol of write is to write one byte to the output stream. The bytes to be written are the eight low bits of parameter b. The 24 high positions of b will be ignored. That is, it is written to the
Void write (byte [] b)
Writes b.length bytes from the specified byte array to this output stream. The general convention of write (b) is that it should have exactly the same effect as a call to wite (breco 0rem B. length).
Void write (byte [] bmenint off,int len)
Writes the len bytes from the offset off in the specified byte array to this output stream.
Public void flush () throws IOException
Refresh this output stream and force all buffered output bytes to be written out, and this method is called to indicate that these bytes should be written immediately to their expected destination.
Public void close throws IOException
Close this transport stream and release all system resources associated with the stream.
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. That is, a Unicode code between 0 and 65535 is written.
Void write (char [] cbuf)
Write character array
Void write (char [] cbuf,int off,int len)
Writes a portion of the character array. Starting with off, write len characters
Void write (String str)
Write a string.
Void write (String str,int off,int len)
Write a portion of a string.
Void flush ()
Refresh the buffers of the stream, they are immediately written to the expected destination.
Public void close throws IOException
Close this output stream and release all system resources associated with the stream
4. Input and output standardization process 4.1 input process:
① creates an object of the File class that indicates the source of the data read. (this file is required to exist)
② creates the corresponding input stream and passes the object of the File class as a parameter to the constructor of the stream.
The specific reading process of ③: create the corresponding byte [] or char [].
④ closes streaming resources
Note: exceptions in the program need to be handled by try-catch-finally.
4.2 output process:
① creates an object of the File class, indicating the location of the written data. (this file is not required to exist)
② creates the corresponding output stream and passes the object of the File class as a parameter to the constructor of the stream.
The specific writing process of ③: write (char [] / byte [] buffer,0,len)
④ closes streaming resources
Note: exceptions in the program need to be handled by try-catch-finally.
3. Node stream (file stream) 1. File character stream FileReader and FileWriter using 1.1 file input
Read from file to memory (program)
Steps:
Create a stream object and load an existing file into the stream FileReader fr = new FileReader (new File ("Test. Txt"))
Create an array char [] ch = new char [1024] that temporarily stores data
Call the read method of the stream object to read the data in the stream into the array. Fr.read (ch)
Close the resource. Fr.close ()
Code example:
@ Testpublic void testFileReader1 () {FileReader fr = null; try {/ / 1.File class instantiation File file = new File ("hello.txt"); / / 2.FileReader stream instantiation fr = new FileReader (file); / / 3. Read in operation / / read (char [] cbuf): returns the number of characters read into the cbuf array each time. If the end of the file is reached, return-1 char [] cbuf = new char [5]; int len; while ((len = fr.read (cbuf))! =-1) {String str = new String (cbuf,0,len); System.out.print (str);}} catch (IOException e) {e.printStackTrace () } finally {if (fr! = null) {/ / 4. Shutdown of the resource try {fr.close ();} catch (IOException e) {e.printStackTrace ();}
Note:
Understanding of read (): returns a character read in. If the end of the file is reached, return-1
Exception handling: in order to ensure that flow resources must be able to perform a close operation. Need to use try-catch-finally processing
The file you read must exist, otherwise it will be reported to FileNotFoundException.
1.2 output of files
From memory (programs) to hard disk files
Steps:
Create a stream object and set up a data storage file File Writer fw = new File Writer (new File ("Test.txt"))
Call the write method of the stream object to write the data to the stream fw.write ("HelloWord")
Close the stream resource and empty the data from the stream to a file. Fw.close ()
Code example:
@ Testpublic void testFileWriter () {FileWriter fw = null; try {/ / 1. Provide an object of the File class, indicating the file File file = new File ("hello1.txt") written to; / / 2. An object that provides FileWriter for writing out data fw = new FileWriter (file,false); / / 3. The written operation fw.write ("I have a dream!\ n"); fw.write ("you need to have a dream!");} catch (IOException e) {e.printStackTrace ();} finally {/ / 4. If (fw! = null) {try {fw.close ();} catch (IOException e) {e.printStackTrace ();} 1.3Quick
Realize the copy operation of text file
Testpublic void testFileReaderFileWriter () {FileReader fr = null; FileWriter fw = null; try {/ / 1. Create an object of the File class, indicating that the files read in and out are File srcFile = new File ("hello.txt"); File destFile = new File ("hello2.txt"); / / you cannot use character streams to process byte data such as pictures / / File srcFile = new File ("test.jpg"); / / File destFile = new File ("test1.jpg") / / 2. Create objects for input stream and output stream fr = new FileReader (srcFile); fw = new FileWriter (destFile); / / 3. Data read and write operations char [] cbuf = new char [5]; int len;// records the number of characters read into the cbuf array while ((len = fr.read (cbuf))! =-1) {/ / write out len characters fw.write (cbuf,0,len);}} catch (IOException e) {e.printStackTrace () } finally {/ / 4. Close the stream resource try {if (fw! = null) fw.close ();} catch (IOException e) {e.printStackTrace ();} try {if (fr! = null) fr.close ();} catch (IOException e) {e.printStackTrace () } 2. The use of file byte stream FileInputSteam and FileOutputSteam
File byte stream operations are similar to character stream operations, except that instantiated object operations and data types are different.
Code example:
/ / using byte stream FileInputStream to deal with text files, garbled may occur. @ Testpublic void testFileInputStream () {FileInputStream fis = null; try {/ / 1. Create the file File file = new File ("hello.txt"); / / 2. Fis = new FileInputStream (file); / / 3. Read data byte [] buffer = new byte [5]; int len;// records the number of bytes read each time while ((len = fis.read (buffer))! =-1) {String str = new String (buffer,0,len); System.out.print (str);}} catch (IOException e) {e.printStackTrace () } finally {if (fis! = null) {/ / 4. Close the resource try {fis.close ();} catch (IOException e) {e.printStackTrace ();}
A little exercise
Realize the copy operation of picture file
Testpublic void testFileInputOutputStream () {FileInputStream fis = null; FileOutputStream fos = null; try {/ / 1. Create the File object File srcFile = new File ("test.jpg"); File destFile = new File ("test2.jpg"); / / 2. Create fis = new FileInputStream (srcFile); fos = new FileOutputStream (destFile); / / 3. The process of copying byte [] buffer = new byte [5]; int len; while ((len = fis.read (buffer))! =-1) {fos.write (buffer,0,len);}} catch (IOException e) {e.printStackTrace ();} finally {/ / 4. Close the stream if (fos! = null) {/ / try {fos.close ();} catch (IOException e) {e.printStackTrace ();}} if (fis! = null) {try {fis.close () } catch (IOException e) {e.printStackTrace ();} 3. Pay attention
When defining a path, you can use "/" or "\".
Output operation, the corresponding File may not exist. It doesn't report anything unusual.
If the file on the hard disk corresponding to the File does not exist, it will be created automatically during the export process.
If the file on the hard disk corresponding to File exists:
If the constructor used by the stream is: FileWriter (file,false) / FileWriter (file): overwrite the original file.
If the constructor used by the stream is: FileWriter (file,true): it does not overwrite the original file, but appends the content to the original file.
When reading a file, you must ensure that the file exists, otherwise an exception will be reported.
For text files (.txt, .java, .c, .cpp), use character stream processing
For non-text files (.jpg, .mp3, .mp4, .avi, .doc, .ppt,...), use byte stream processing
4. Buffer stream 1. The classes involved in the buffer flow:
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
two。 Purpose of introduction:
Function: provides the speed of reading and writing streams
The reason for improving the speed of reading and writing: a buffer is provided internally. 8kb by default
Comparative diagram of processing flow and node flow
3. instructions
When data is read, the data is read into the buffer in blocks, and subsequent reads access the buffer directly.
When you use BufferedInputStream to read a byte file, BufferedInputStream reads 8192 (8Kb) from the file at once and stores it in the buffer until the buffer is full before re-reading the next 8192-byte array from the file.
When writing bytes to the stream, it is not written directly to the file, but is written to the buffer until the buffer is full before BufferedOutputStream writes the data in the buffer to the file at one time. Use the method flush () to force the contents of the buffer to be written to the output stream.
The order in which the stream is closed is the opposite of the order in which the stream is opened. As long as you turn off the outermost laminar flow, turning off the outermost laminar flow will also close the inner node flow accordingly.
The use of the flush () method: manually writes the contents of the buffer to the file.
If it is the close () method of a stream object with a buffer, it not only closes the stream, but also flushes the buffer before closing the stream, which can no longer be written out.
Code example:
Use BufferInputStream and BufferOutputStream to copy non-text files @ Testpublic void testBufferedStream () {BufferedInputStream bis = null; BufferedOutputStream bos = null; try {/ / 1. Create documents File srcFile = new File ("test.jpg"); File destFile = new File ("test4.jpg"); / / 2. FileInputStream fis = new FileInputStream (srcFile); FileOutputStream fos = new FileOutputStream (destFile); / / 2.2 create buffered streams, which can be combined to write bis = new BufferedInputStream (fis); bos = new BufferedOutputStream (fos); / / 3. File read and write operations byte [] buffer = new byte [1024]; int len; while ((len = bis.read (buffer))! =-1) {bos.write (buffer,0,len);}} catch (IOException e) {e.printStackTrace ();} finally {/ / 4. Close the stream if (bos! = null) {try {bos.close ();} catch (IOException e) {e.printStackTrace ();}} if (bis! = null) {try {bis.close () } catch (IOException e) {e.printStackTrace ();} 3.2 copy of text files using BufferedReader and BufferedWriter @ Testpublic void testBufferedReaderBufferedWriter () {BufferedReader br = null; BufferedWriter bw = null; try {/ / create files and corresponding stream br = new BufferedReader (new File ("dbcp.txt") Bw = new BufferedWriter (new FileWriter (new File ("dbcp1.txt"); / / read and write operations / / method 1: use char [] array / / char [] cbuf = new char [1024]; / / int len / / while ((len = br.read (cbuf))! =-1) {/ / bw.write (cbuf,0,len); / bw.flush (); / /} / / method 2: use String String data While ((data = br.readLine ())! = null) {/ / method 1: / / bw.write (data + "\ n"); / / data does not contain newline character / / method 2: bw.write (data); / / data does not contain newline character bw.newLine () / / provide line wrapping}} catch (IOException e) {e.printStackTrace ();} finally {/ / close resource if (bw! = null) {try {bw.close ();} catch (IOException e) {e.printStackTrace () } if (br! = null) {try {br.close ();} catch (IOException e) {e.printStackTrace ();} 4. Small exercise 4.1 Test buffer flow and Node flow File replication Speed
Replication method for Node flow
/ / copy public void copyFile (String srcPath,String destPath) {FileInputStream fis = null; FileOutputStream fos = null; try {/ / 1 of the file under the specified path. Create documents File srcFile = new File (srcPath); File destFile = new File (destPath); / / 2. Fis = new FileInputStream (srcFile); fos = new FileOutputStream (destFile); / / 3. The process of copying byte [] buffer = new byte [1024]; int len; while ((len = fis.read (buffer))! =-1) {fos.write (buffer,0,len);}} catch (IOException e) {e.printStackTrace ();} finally {if (fos! = null) {/ / 4. Close the stream try {fos.close ();} catch (IOException e) {e.printStackTrace ();}} if (fis! = null) {try {fis.close ();} catch (IOException e) {e.printStackTrace () }
The buffer stream implements the copy operation
/ / public void copyFileWithBuffered (String srcPath,String destPath) {BufferedInputStream bis = null; BufferedOutputStream bos = null; try {/ / 1. Create documents File srcFile = new File (srcPath); File destFile = new File (destPath); / / 2. FileInputStream fis = new FileInputStream ((srcFile)); FileOutputStream fos = new FileOutputStream (destFile); / / 2.2 make buffer flow bis = new BufferedInputStream (fis); bos = new BufferedOutputStream (fos); / / 3. Copy details: read and write byte [] buffer = new byte [1024]; int len; while ((len = bis.read (buffer))! =-1) {bos.write (buffer,0,len);}} catch (IOException e) {e.printStackTrace ();} finally {/ / 4. Resource shutdown / / requirement: first close the outer stream, then close the inner stream if (bos! = null) {try {bos.close ();} catch (IOException e) {e.printStackTrace () } if (bis! = null) {try {bis.close ();} catch (IOException e) {e.printStackTrace ();}
Test the speed of both
@ Testpublic void testCopyFileWithBuffered () {long start = System.currentTimeMillis (); String srcPath = "C:\\ Users\\ Administrator\\ Desktop\\ 01-video .avi"; String destPath = "C:\\ Users\\ Administrator\\ Desktop\\ 03-video .avi"; copyFileWithBuffered (srcPath,destPath); long end = System.currentTimeMillis (); System.out.println ("the time taken by the copy operation is" + (end-start)) / / 618-176} 4.2 implement image encryption operation
Encryption operation
Read the picture file into the program through byte stream
^ operate the byte stream of the picture one by one
Output the processed picture byte stream
/ / encryption @ Testpublic void test1 () {FileInputStream fis = null; FileOutputStream fos = null; try {fis = new FileInputStream ("test.jpg"); fos = new FileOutputStream ("testSecret.jpg"); byte [] buffer = new byte [20]; int len; while ((len = fis.read (buffer))! =-1) {for (int I = 0; I)
< len; i++) { buffer[i] = (byte) (buffer[i] ^ 5); } fos.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } }} 解密操作 将加密后图片文件通过字节流读取到程序中 将图片的字节流逐一进行^操作(原理:A^B^B = A) 将处理后的图片字节流输出 //图片的解密@Testpublic void test2() { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream("testSecret.jpg"); fos = new FileOutputStream("test4.jpg"); byte[] buffer = new byte[20]; int len; while ((len = fis.read(buffer)) != -1) { for (int i = 0; i < len; i++) { buffer[i] = (byte) (buffer[i] ^ 5); } fos.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } }}4.3 统计文本字符出现次数 实现思路: 遍历文本每一个字符 字符出现的次数存在Map中 把map中的数据写入文件 @Testpublic void testWordCount() { FileReader fr = null; BufferedWriter bw = null; try { //1.创建Map集合 Map map = new HashMap(); //2.遍历每一个字符,每一个字符出现的次数放到map中 fr = new FileReader("dbcp.txt"); int c = 0; while ((c = fr.read()) != -1) { //int 还原 char char ch = (char) c; // 判断char是否在map中第一次出现 if (map.get(ch) == null) { map.put(ch, 1); } else { map.put(ch, map.get(ch) + 1); } } //3.把map中数据存在文件count.txt //3.1 创建Writer bw = new BufferedWriter(new FileWriter("wordcount.txt")); //3.2 遍历map,再写入数据 Set entrySet = map.entrySet(); for (Map.Entry entry : entrySet) { switch (entry.getKey()) { case ' ': bw.write("空格=" + entry.getValue()); break; case '\t'://\t表示tab 键字符 bw.write("tab键=" + entry.getValue()); break; case '\r':// bw.write("回车=" + entry.getValue()); break; case '\n':// bw.write("换行=" + entry.getValue()); break; default: bw.write(entry.getKey() + "=" + entry.getValue()); break; } bw.newLine(); } } catch (IOException e) { e.printStackTrace(); } finally { //4.关流 if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } }}五、转换流1. 简介 转换流提供了在字节流和字符流之间的转换 Java API提供了两个转换流: InputstreamReader:将 Inputstream转换为Reader OutputStreamWriter:将 Writer转换为OutputStream 字节流中的数据都是字符时,转成字符流操作更高效。 很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。 1.1 InputStreamReader InputStreamReader将一个字节的输入流转换为字符的输入流 解码:字节、字节数组 --->Character array, string
Constructor:
Public InputStreamReader (InputStream in)
Public InputStreamReader (Inputstream in,String charsetName) / / you can specify a code set
1.2 OutputStreamWriter
OutputStreamWriter converts the output stream of a character into the output stream encoding of bytes: character array, string-- > bytes, byte array
Constructor:
Public OutputStreamWriter (OutputStream out)
Public OutputStreamWriter (Outputstream out,String charsetName) / / you can specify a code set
The figure shows:
two。 Code example: / * * combine InputStreamReader and OutputStreamWriter * / @ Testpublic void test1 () {InputStreamReader isr = null; OutputStreamWriter osw = null; try {/ / 1. File file1 = new File ("dbcp.txt"); File file2 = new File ("dbcp_gbk.txt"); FileInputStream fis = new FileInputStream (file1); FileOutputStream fos = new FileOutputStream (file2); isr = new InputStreamReader (fis, "utf-8"); osw = new OutputStreamWriter (fos, "gbk"); / / 2. Char [] cbuf = new char [20]; int len; while ((len = isr.read (cbuf))! =-1) {osw.write (cbuf,0,len);}} catch (IOException e) {e.printStackTrace ();} finally {/ / 3. If (isr! = null) {try {isr.close ();} catch (IOException e) {e.printStackTrace ();}} if (osw! = null) {try {osw.close () } catch (IOException e) {e.printStackTrace ();}
Description: the way the file is encoded (for example: GBK) determines the character set used when parsing (only GBK).
3. Code set 3.1 Common coding tables
ASCII: American standard information interchange code. It can be represented by 7 bits of a byte.
ISO8859-1: Latin code table. The Eurocode table is represented by 8 bits of a byte.
GB2312: Chinese coding table in China. Up to two bytes encode all characters
GBK: China's Chinese code table has been upgraded to incorporate more Chinese text symbols. Up to two byte encoding
Unicode: international standard code, which integrates the characters currently used by human beings. Assign a unique character code to each character. All words are represented by two bytes.
UTF-8: variable length encoding in which a character can be represented by 1-4 bytes.
Description:
Many transport-oriented UTF (UCS Transfer Format) standards have emerged. as the name implies, UTF-8 transfers data 8 bits at a time, while UTF-16 transfers data 16 bits at a time. This is a code designed for transmission and makes it borderless so that characters from all cultures in the world can be displayed.
Unicode simply defines a large, universal character set, and specifies only a definite number for each character, depending on the character coding scheme. The recommended Unicode codes are UTF-8 and UTF-16.
UTF-8 variable length coding representation
3.2 coding application
Encoding: string-- > byte array
Decoding: byte array-- > string
Coding Application of conversion Stream
Characters can be stored in a specified encoding format
Text data can be interpreted in a specified encoding format
Specifies that the action of the coding table is done by the constructor
Requirements for use:
Client / browser-side background (java,GO,Python,Node.js,php) database
It is required that the character set used before and after should be unified: UTF-8.
6. Standard input and output streams 1. Brief introduction
System.in: standard input stream, input from keyboard by default
System.out: standard output stream, output from the console by default
two。 Main methods
The setIn (InputStream is) mode of the System class reassigns the stream of the input
The setOut (PrintStream ps) mode of the System class reassigns the output stream.
3. Use the example
Entering a string from the keyboard requires that the entire line of string read be converted to uppercase output. Then continue with the input operation
Exit the program until you type "e" or "exit".
Design ideas
Method 1: use Scanner to implement and call next () to return a string
Method 2: use System.in to implement. System.in-> conversion stream-> readLine () of BufferedReader
Public static void main (String [] args) {BufferedReader br = null; try {InputStreamReader isr = new InputStreamReader (System.in); br = new BufferedReader (isr); while (true) {System.out.println ("Please enter string:"); String data = br.readLine () If ("e" .equalsIgnoreCase (data) | | "exit" .equalsIgnoreCase (data)) {System.out.println ("Program ends"); break;} String upperCase = data.toUpperCase (); System.out.println (upperCase);}} catch (IOException e) {e.printStackTrace () } finally {if (br! = null) {try {br.close ();} catch (IOException e) {e.printStackTrace ();} 4. A little exercise
Design and implementation of Scanner class
Public class MyInput {/ / Read a string from the keyboard public static String readString () {BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); / / Declare and initialize the string String string = ""; / / Get the string from the keyboard try {string = br.readLine ();} catch (IOException ex) {System.out.println (ex) } / / Return the string obtained from the keyboard return string;} / / Read an int value from the keyboard public static int readInt () {return Integer.parseInt (readString ());} / / Read a double value from the keyboard public static double readDouble () {return Double.parseDouble (readString ()) } / / Read a byte value from the keyboard public static double readByte () {return Byte.parseByte (readString ());} / Read a short value from the keyboard public static double readShort () {return Short.parseShort (readString ());} / / Read a long value from the keyboard public static double readLong () {return Long.parseLong (readString ()) } / / Read a float value from the keyboard public static double readFloat () {return Float.parseFloat (readString ());}} VII. Print stream
PrintStream and PrintWriter instructions:
Provides a series of overloaded print () and println () methods for output of multiple data types
System.out returns an instance of PrintStream
@ Testpublic void test2 () {PrintStream ps = null; try {FileOutputStream fos = new FileOutputStream (new File ("D:\\ IO\\ text.txt")); / / create the printout stream, which is set to auto refresh mode (the output buffer is flushed when line breaks or bytes are written) ps = new PrintStream (fos, true) If (ps! = null) {/ / convert the standard output stream (console output) to a file System.setOut (ps);} for (int I = 0; I files stored, transferred over the network: serialization process
ObjectInputStream: files in storage, received over the network-> objects in memory: deserialization process
3. Serialization of objects
The object serialization mechanism allows Java objects in memory to be converted into platform-independent binary streams, thus allowing the binary stream to be persisted on disk or transmitted to another network node over the network. / / when other programs acquire this binary stream, they can revert to the original Java object.
The advantage of serialization is that any object that implements the Serializable interface can be converted into byte data so that it can be restored when saved and transferred.
Serialization is a mechanism that must be implemented for both parameters and return values of RMI (Remote Method Invoke- remote method invocation) procedures, and RMI is the foundation of JavaEE. So the serialization mechanism is the foundation of the JavaEE platform.
If you need an object to support a serialization mechanism, you must make the class to which the object belongs and its properties serializable, and in order for a class to be serializable, the class must implement one of the following two interfaces. Otherwise, a NotserializableEXception exception will be 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 compatibility between different versions of a class. In short, the purpose is to version control with serialized objects, which is about whether each version is compatible when deserializing.
If the class does not show the definition of this static constant, its value is automatically generated by the Java runtime environment based on the internal details of the class. If the instance variable of the class is modified, the serialVersionUID may change. It is therefore recommended to make an explicit declaration.
To put it simply, Java's serialization mechanism verifies version consistency by determining the serialversionUID of the class at run time. When deserializing, JVM compares the serialversionUID in the incoming byte stream with the serialversionUID of the corresponding local entity class. If the same is considered to be consistent, it can be deserialized, otherwise an exception of inconsistent serialization version will occur. (InvalidCastException)
4. The class to which the serialized object belongs needs to meet:
Need to implement the interface: Serializable (identity interface)
The current class provides a global constant: serialVersionUID (sequence version number)
In addition to the current Person class that needs to implement the Serializable interface, you must also ensure that all of its internal properties must be serializable. (basic data types are serializable by default)
Add: ObjectOutputStream and ObjectInputStream cannot serialize member variables modified by static and transient
5. Implementation of object flow using 5.1 serialization code
Serialization: writing objects to disk or network transfer
Requires that serialized objects must be serialized
@ Testpublic void testObjectOutputStream () {ObjectOutputStream oos = null; try {/ / 1. Create an object and create a stream oos = new ObjectOutputStream (new FileOutputStream ("object.dat")); / / 2. Operation flow oos.writeObject (new String ("I love Beijing Tiananmen"); oos.flush (); / refresh operation oos.writeObject (new Person ("Wang Ming", 23)); oos.flush (); oos.writeObject (new Person ("Zhang Xueliang", 23jie 1001 new Account (5000)); oos.flush ();} catch (IOException e) {e.printStackTrace () } finally {if (oos! = null) {/ / 3. Close the stream try {oos.close ();} catch (IOException e) {e.printStackTrace ();} 5.2 deserialization code implementation
Deserialization: read out the object data source of the disk
@ Testpublic void testObjectInputStream () {ObjectInputStream ois = null; try {ois = new ObjectInputStream (new FileInputStream ("object.dat")); Object obj = ois.readObject (); String str = (String) obj; Person p = (Person) ois.readObject (); Person p1 = (Person) ois.readObject (); System.out.println (str); System.out.println (p) System.out.println (p1);} catch (IOException e) {e.printStackTrace ();} catch (ClassNotFoundException e) {e.printStackTrace ();} finally {if (ois! = null) {try {ois.close ();} catch (IOException e) {e.printStackTrace () 10. Arbitrary access to the file stream
The use of RandomAccessFile
1. Brief introduction
RandomAccessFile inherits directly from the java.lang.Object class and implements DataInput and DataOutput interfaces.
RandomAccessFile can be used as both an input stream and an output stream
The RandomAccessFile class supports "random access", and the program can jump to any place of the file to read and write the file.
Support to access only part of the file
You can append content to an existing file
The RandomAccessFile object contains a record pointer that indicates the location of the current read and write.
RandomaccessFile class objects are free to move the record pointer:
Long getFilePointer (): gets the current location of the file record pointer
Void seek (long pos): position the file record pointer to the pos location
Constructor
Public RandomAccessFile (File file,String mode)
Public RandomAccessFile (String name,String mode)
two。 Instructions for use:
If the file written out does not exist when RandomAccessFile is used as the output stream, it is automatically created during execution.
If the written file exists, the contents of the original file are overwritten. (overrides from scratch by default)
You can achieve the effect of RandomAccessFile "inserting" data through related operations. By means of seek (int pos) method
To create an instance of the RandomAccessFile class, you need to specify a mode parameter that specifies the access mode of the RandomAccessFile:
R: open as read-only
Rw: open for reading and writing
Rwd: open for reading and writing; synchronize updates to file contents
Rws: open for reading and writing; synchronize updates to file contents and metadata
If the mode is read-only r, a file is not created, but a file that already exists is read, and an exception occurs if the read file does not exist. If the mode is rw read and write, the file will be created if it does not exist, but not if it exists.
3. Use the example
Read and write operations of files
Testpublic void test1 () {RandomAccessFile raf1 = null; RandomAccessFile raf2 = null; try {/ / 1. Create object, create stream raf1 = new RandomAccessFile (new File ("test.jpg"), "r"); raf2 = new RandomAccessFile (new File ("test1.jpg"), "rw"); / / 2. Operation flow byte [] buffer = new byte [1024]; int len; while ((len = raf1.read (buffer))! =-1) {raf2.write (buffer,0,len);}} catch (IOException e) {e.printStackTrace ();} finally {/ / 3. Close the stream if (raf1! = null) {try {raf1.close ();} catch (IOException e) {e.printStackTrace ();}} if (raf2! = null) {try {raf2.close () } catch (IOException e) {e.printStackTrace ();}
Using RandomAccessFile to achieve the effect of data insertion
Testpublic void test2 () {RandomAccessFile raf1 = null; try {raf1 = new RandomAccessFile (new File ("hello.txt"), "rw"); raf1.seek (3) / / set the pointer to the position marked at the corner 3 / method 1 / / save all data after pointer 3 to StringBuilder / / StringBuilder builder = new StringBuilder ((int) new File ("hello.txt") .length ()); / / byte [] buffer = new byte [20] / / int len; / / while ((len = raf1.read (buffer))! =-1) {/ / builder.append (new String (buffer,0,len)); / /} / / Mode 2 ByteArrayOutputStream baos = new ByteArrayOutputStream (); byte [] buffer = new byte [20]; int len While ((len = raf1.read (buffer))! =-1) {baos.write (buffer);} / recall the pointer to write "xyz" raf1.seek (3); raf1.write ("xyz" .getBytes ()); / / write the data from StringBuilder to the file raf1.write (baos.toString (). GetBytes ()) } catch (IOException e) {e.printStackTrace ();} finally {if (raf1! = null) {try {raf1.close ();} catch (IOException e) {e.printStackTrace ();} 11. Summary of basic applications of streams
Streams are used to process data.
When dealing with data, be sure to specify the data source, and the data destination data source can be a file, a keyboard data destination can be a file, a monitor or other device
On the other hand, the stream is just helping to transmit the data and process the transmitted data, such as filtering, conversion processing, etc.
All flows except the RandomAccessFile class inherit from the four basic data flow abstract classes InputSteam, OutputSteam, Reader, and Writer
The suffix corresponding to different operation flows is one of the four abstract base classes.
The use of different processing streams is standard:
Create a file object and create a corresponding stream
Processing stream data
Close the stream
Handling exceptions with try-catch-finally
12. NIO
Path, Paths, Files use, the introduction is relatively simple, later will take the time to write a detailed blog about NIO.
Instructions for using 1.NIO:
Java NIO (New IO,Non-Blocking IO) is a new set of IO API introduced from Java 1.4, which can replace the standard Java IO AP.
NIO has the same function and purpose as the original IO, but in a completely different way. NIO supports buffer-oriented (IO is stream-oriented), channel-based IO operations.
NIO will read and write files in a more efficient way.
JDK 7.0 greatly extends NIO to enhance support for file processing and file system features, calling it NIO.2.
Two sets of NIO are provided in Java API, one for standard input and output NIO The other is network programming NIO |-java.nio.channels.Channel |-FileChannel: processing local files |-SocketChannel:TCP network programming client Channel |-ServerSocketChannel:TCP network programming server-side Channel |-DatagramChannel:UDP network programming Channel2.Path interface between sender and receiver-provided by JDK 7.0.
Early Java provided only one File class to access the file system, but the functionality of the File class was limited and the performance of the methods provided was not high. Moreover, most methods only return a failure when something goes wrong and do not provide exception information.
In order to make up for this deficiency, NIO.2 introduces the Path interface, which represents a platform-independent platform path and describes the location of files in the directory structure. Path can be thought of as an upgraded version of the File class, and the actual referenced resource may not exist.
Description of 2.1Path:
Path replaces the original File class.
In the past, the IO operation was written like this:
Import java.io.File
File file = new File ("index.html")
But in Java7, we can write like this:
Import java.nio.file.Path
Import java.nio.file.Paths
Path path = Paths.get ("index. Html")
2.2 use of Paths
The static get () method provided by the Paths class is used to get the Path object:
Static Path get (String first, String... .more): used to concatenate multiple strings into a path
Static Path get (URI uri): returns the Path path corresponding to the specified uri
Code example
@ Testpublic void test1 () {Path path2 = Paths.get ("hello.txt"); / / new File (String filepath) Path path3 = Paths.get ("E:\\", "test\\ test1\\ .txt"); / / new File (String parent,String filename); Path path4 = Paths.get ("E:\", "test"); System.out.println (path2); System.out.println (path3); System.out.println (path4) } 2.3 Common methods
String toString (): returns the string representation of the calling Path object
Boolean startsWith (String path): determines whether to start with a path path
Boolean endsWith (String path): determines whether to end with a path path
Boolean isAbsolute (): determines whether it is an absolute path
Path getParent (): returns the Path object contains the entire path and does not contain the file path specified by the Path object
Path getRoot (): returns the root path where the Path object is called
Path getFileName (): returns the file name associated with the call to the Path object
Int getNameCount (): returns the number of elements following the Path root directory
Path getName (int idx): returns the path name of the specified index location idx
Path toAbsolutePath (): calls the Path object as an absolute path return
Path resolve (Path p): merges two paths and returns the Path object corresponding to the merged path
File toFile (): converts Path to an object of the File class
Code example
@ Testpublic void test2 () {Path path2 = Paths.get ("d:\", "nio\\ nio1\\ nio2\\ hello.txt"); Path path3 = Paths.get ("hello.txt"); / / String toString (): returns the string representation of the calling Path object System.out.println (path2) / / boolean startsWith (String path): determine whether to start System.out.println with the path path (path2.startsWith ("d:\\ nio")); / / boolean endsWith (String path): determine whether to end the System.out.println with the path path (path2.endsWith ("hello.txt")) / / boolean isAbsolute (): determine whether the absolute path is System.out.println (path2.isAbsolute () + "~"); System.out.println (path3.isAbsolute () + "~"); / / Path getParent (): return the Path object contains the entire path, not the file path specified by the Path object System.out.println (path2.getParent ()) System.out.println (path3.getParent ()); / / Path getRoot (): returns the root path of the calling Path object System.out.println (path2.getRoot ()); System.out.println (path3.getRoot ()); / / Path getFileName (): returns the file name System.out.println (path2.getFileName () + "~") associated with the calling Path object. System.out.println (path3.getFileName () + "~"); / / int getNameCount (): returns the number of elements following the Path root directory / / Path getName (int idx): returns the path name for (int I = 0; I) of the specified index location idx
< path2.getNameCount(); i++) { System.out.println(path2.getName(i) + "*****"); } // Path toAbsolutePath() : 作为绝对路径返回调用 Path 对象 System.out.println(path2.toAbsolutePath()); System.out.println(path3.toAbsolutePath()); // Path resolve(Path p) :合并两个路径,返回合并后的路径对应的Path对象 Path path4 = Paths.get("d:\\", "nio"); Path path5 = Paths.get("nioo\\hi.txt"); path4 = path4.resolve(path5); System.out.println(path4); // File toFile(): 将Path转化为File类的对象 File file = path2.toFile();//Path--->Conversion Path newPath of File = file.toPath (); / / conversion} 3.Files class of File--- > Path
A tool class used by java.nio.file.Files to manipulate a file or directory
3.1 Common methods of Files class
Path copy (Path src, Path dest, CopyOption... How): copy of fil
In order to copy successfully, the physical file corresponding to path2 is required to exist. The file corresponding to path2 is not required.
Files.copy (path2, path3, StandardCopyOption.REPLACE_EXISTING)
Path createDirectory (Path path, FileAttribute... Attr): create a directory
To execute successfully, the physical file directory corresponding to path does not exist. Once it exists, an exception is thrown.
Path createFile (Path path, FileAttribute... Arr): create a file
For the execution to succeed, the physical file corresponding to the path does not exist. Once it exists, an exception is thrown.
Void delete (Path path): delete a file / directory and execute an error message if it does not exist
Void deleteIfExists (Path path): delete the file / directory corresponding to Path if it exists. If it does not exist, the normal execution ends
Path move (Path src, Path dest, CopyOption... How): move src to dest location
In order to execute successfully, the physical file corresponding to src needs to exist, and the file corresponding to dest is not required.
Long size (Path path): returns the size of the file specified by path
Code example
@ Testpublic void test1 () throws IOException {Path path2 = Paths.get ("d:\\ nio", "hello.txt"); Path path3 = Paths.get ("atguigu.txt"); / / Path copy (Path src, Path dest, CopyOption... How): the copy of the file / / in order to copy successfully, the physical file corresponding to path2 is required to exist. The file corresponding to path2 is not required. / / Files.copy (path2, path3, StandardCopyOption.REPLACE_EXISTING); / / Path createDirectory (Path path, FileAttribute … Attr): create a directory / / to execute successfully, the physical file directory corresponding to path does not exist. Once it exists, an exception is thrown. Path path4 = Paths.get ("d:\\ nio\\ nio1"); / / Files.createDirectory (path4); / / Path createFile (Path path, FileAttribute... Arr): create a file / / to execute successfully, the physical file corresponding to path does not exist. Once it exists, an exception is thrown. Path path5 = Paths.get ("d:\\ nio\\ hi.txt"); / / Files.createFile (path5); / / void delete (Path path): delete a file / directory, if it does not exist, execute error / / Files.delete (path5) / / void deleteIfExists (Path path): delete the file / directory corresponding to Path if it exists. If it does not exist, execute the end Files.deleteIfExists (path4) normally; / / Path move (Path src, Path dest, CopyOption... How): move src to dest location / / for successful execution, the physical file corresponding to src needs to exist, while the file corresponding to dest is not required. / / Files.move (path2, path3, StandardCopyOption.ATOMIC_MOVE); / / long size (Path path): returns the size of the file specified by path long size = Files.size (path3); System.out.println (size);} 3.2Common methods of Files class: used to determine
Boolean exists (Path path, LinkOption... Opts): determine whether the file exists
Boolean isDirectory (Path path, LinkOption... Opts): determine whether it is a directory or not
The physical file for this path is not required to exist.
Boolean isRegularFile (Path path, LinkOption... Opts): determine whether it is a file or not
Boolean isHidden (Path path): determines whether a file is hidden
The physical file corresponding to this path is required to exist. To determine whether it's hidden or not. Otherwise, an exception is thrown.
Boolean isReadable (Path path): determines whether a file is readable
Boolean isWritable (Path path): determines whether a file is writable or not
Boolean notExists (Path path, LinkOption... Opts): determine whether the file does not exist
Code example
@ Testpublic void test2 () throws IOException {Path path2 = Paths.get ("d:\\ nio", "hello.txt"); Path path3 = Paths.get ("atguigu.txt"); / / boolean exists (Path path, LinkOption... Opts): determine whether System.out.println (Files.exists (path3, LinkOption.NOFOLLOW_LINKS)) exists in the file; / / boolean isDirectory (Path path, LinkOption... Opts): determine whether it is a directory / / the physical file corresponding to this path is not required to exist. System.out.println (Files.isDirectory (path2, LinkOption.NOFOLLOW_LINKS)); / / boolean isRegularFile (Path path, LinkOption … Opts): determine whether it is a file / / boolean isHidden (Path path): determine whether it is a hidden file / / require the physical file corresponding to this path to exist. To determine whether it's hidden or not. Otherwise, an exception is thrown. / / System.out.println (Files.isHidden (path2)); / / boolean isReadable (Path path): determine whether a file is readable System.out.println (Files.isReadable (path2)); / / boolean isWritable (Path path): determine whether a file is writable System.out.println (Files.isWritable (path2)); / / boolean notExists (Path path, LinkOption... Opts): determine whether the file does not exist System.out.println (Files.notExists (path2, LinkOption.NOFOLLOW_LINKS));}
Add:
StandardOpenOption.READ: indicates that the corresponding Channel is readable.
StandardOpenOption.WRITE: indicates that the corresponding Channel is writable.
StandardOpenOption.CREATE: if the file to be written out does not exist, create it. If it exists, ignore
StandardOpenOption.CREATE_NEW: if the file to be written out does not exist, create it. If it exists, throw an exception
3.3Common methods of Files class: used to manipulate content
InputStream newInputStream (Path path, OpenOption... How): get the InputStream object
OutputStream newOutputStream (Path path, OpenOption... How): get the OutputStream object
SeekableByteChannel newByteChannel (Path path, OpenOption... How): gets the connection to the specified file, and how specifies how to open it.
DirectoryStream newDirectoryStream (Path path): opens the directory specified by path
Code example
@ Testpublic void test3 () throws IOException {Path path2 = Paths.get ("d:\\ nio", "hello.txt"); / / InputStream newInputStream (Path path, OpenOption... How): get the InputStream object InputStream inputStream = Files.newInputStream (path2, StandardOpenOption.READ); / / OutputStream newOutputStream (Path path, OpenOption... How): get the OutputStream object OutputStream outputStream = Files.newOutputStream (path2, StandardOpenOption.WRITE,StandardOpenOption.CREATE); / / SeekableByteChannel newByteChannel (Path path, OpenOption... How): gets the connection to the specified file, and how specifies how to open it. SeekableByteChannel channel = Files.newByteChannel (path2, StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE); / / DirectoryStream newDirectoryStream (Path path): open the directory specified by path Path path3 = Paths.get ("e:\\ teach"); DirectoryStream directoryStream = Files.newDirectoryStream (path3); Iterator iterator = directoryStream.iterator (); while (iterator.hasNext ()) {System.out.println (iterator.next ()) }} at this point, the study on the understanding and use of Java File classes is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.