In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Today, the editor will share with you the relevant knowledge points of JAVA IO stream, File, byte stream and character stream instance analysis. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
Introduction to IO 1 Stream
Before learning IO flow, the first concept we need to learn is Stream flow.
For ease of understanding, we can abstract the read and write operations of data into the flow of data in the "pipeline", but we should pay attention to:
1. The flow can only flow in one direction.
two。 The input stream is used to read → in
3. The output stream is used to write out → out
4. Data can only be read and written once in sequence from beginning to end.
So from a program point of view, the input (read) / output (write) process of In/out relative to the program.
2 inheritance structure of IO flow
In java, streams can be divided into byte streams and character streams according to the data units processed.
Byte streams: for binary files
Character streams: for text files
Combined with the input and output directions of the corresponding types, the commonly used streams are:
File byte stream: for binary InputStreamFileInputStreamBufferedInputStreamObjectInputStreamOutputStreamFileOutputStreamBufferedOutputStreamObjectOutputStream character stream: write 3 File file class 3.1 overview for text file ReaderFileReaderBufferedReaderInputStreamReaderWriterFileWriterBufferedWriterOutputStreamWriterPrintWriter one line
Encapsulates a disk path string on which you can perform an operation
Can encapsulate file paths, folder paths, paths that do not exist
3.2 create objects
File (String pathname) creates a new File instance by converting a given pathname string to an abstract pathname
New File ("d:/abc/a.txt")
New File ("d:/abc", "a.txt")
3.3 Common methods
3.4 activity: testing common methods
Create package: cn.tedu.file
Create a class: TestFile.java
Package cn.tedu.file;import java.io.File;import java.io.IOException;import java.util.Arrays;/* this class is used to test the file class File*/public class TestFile {public static void main (String [] args) throws IOException {/ / 1. To create File class objects / * 1.ready directory and 1.txt, you need to manually create * 2.File needs guide package: import java.io.File; * 3. The path is of type String and must be written correctly, otherwise the file * 4 will not be found. The complete file name consists of two parts: file name + suffix name * / File file = new File ("E:\\ ready\\ 1.txt"); / / 2.1 Test the common method System.out.println in File (file.length ()); / / 3, get the number of bytes of the file System.out.println (file.exists ()) / / true, determine whether the file exists System.out.println (file.isFile ()); / / true, determine whether it is a file System.out.println (file.isDirectory ()); / / false, determine whether it is a folder System.out.println (file.getName ()); / / 1.txt get the file name System.out.println (file.getParent ()) / / E:\ ready get the parent path System.out.println (file.getAbsolutePath ()) / / E:\ ready\ 1.txt get the full path with a drive letter: absolute path / / 2.2 Test creation and deletion / * new will only help you create an object of type File in memory * it will not help you create a real 2.txt file on disk * / file = new File ("E:\\ ready\\ 2.txt") / / create a file 2.txt that did not exist before. If it is created successfully, it will return true / * if you specify the wrong path to create the file, an exception will be thrown: java.io.Exception * so you need to deal with this problem in advance. We temporarily choose to throw on main () * this IO exception is a mandatory exception we have encountered that must be handled in advance * if not handled, the call to the method will report an error and fail the compilation * / System.out.println (file.createNewFile ()) / / create a file file = new File ("E:\\ ready\\ m"); System.out.println (file.mkdir ()); / / create a single-tier folder file = new File ("E:\ ready\ a\\ b\ c") that did not exist before; System.out.println (file.mkdirs ()) / / create a multi-tier folder System.out.println (file.delete ()) that did not exist before; / / c is deleted and delete the empty folder or the file file = new File ("E:\ ready\\ a"); System.out.println (file.delete ()); / / the false,a folder is not empty and contains content file = new File ("E:\ ready\\ 2.txt") System.out.println (file.delete ()); / / 2.txt is deleted, you can delete the file / / 2.3.Test presentation file list file = new File ("E:\\ ready"); String [] list = file.list (); / * infrequent * / System.out.println (Arrays.toString (list)) / / this sentence will report an error, because this is a String [], so every element in the array is of type String / / then only the method in the String class can be used, and isDirectory () is the method / / System.out.println (list [0] .isDirectory ()) in the File class; File [] fs = file.listFiles (); / * commonly used * / System.out.println (Arrays.toString (fs)) System.out.println (fs [0] .isDirectory ());}} 4-byte stream read
A byte stream is made up of bytes and a character stream is made up of characters.
The character in Java consists of two bytes. A byte stream is a basic stream that is mainly used to process binary data.
So byte stream is commonly used and can handle many different kinds of files, such as text documents / audio / video and so on.
4.1 InputStream Abstract Class
This abstract class is a superclass / abstract class that represents all classes of the byte input stream, and objects cannot be created.
Common methods:
Abstract int read () reads the next byte of data from the input stream
Int read (byte [] b) reads a certain number of bytes from the input stream and stores them in the buffer array b
Int read (byte [] b, int off, int len) reads up to len data bytes in the input stream into the byte array, and off represents the offset in memory.
Void close () closes this input stream and releases all system resources associated with the stream
4.2 FileInputStream subclass
Insert directly into the file and read the file data directly
Create object
FileInputStream (File file)-transfer the file object directly
Create a FileInputStream by opening a connection to the actual file that specifies the FileInputStream (String pathname)-transfer path through the File object file in the file system
Create a FileInputStream by opening a connection to the actual file, which is specified by the pathname name in the file system
4.3 BufferedInputStream subclass
BufferedInputStream adds some functionality to another input stream, creating an array of internal buffers (default 8k size) when the BufferedInputStream is created. When reading or skipping bytes in the stream, you can repopulate the internal buffer from the included input stream as needed, multiple bytes at a time.
Create object
BufferedInputStream (InputStream in)
Create a BufferedInputStream and save its parameters, the input stream in, for future use.
4.4 activity: byte stream reading case
Create package: cn.tedu.file
Create a class: TestIn.java
Package cn.tedu.file;import java.io.*;/* this class is used to practice byte input stream * / public class TestIn {public static void main (String [] args) {/ / method (); / / byte stream read method2 () / / read of efficient byte stream} / / this method is used to test the read of efficient byte stream private static void method2 () {/ / define a local variable in that takes effect in this method. Note manual initialization. The value is null InputStream in = null; try {/ / 1. Create an efficient byte input stream object / / InputStream in = new BufferedInputStream (/ / new FileInputStream (new File ("E:\\ ready\\ 1.txt")); in = new BufferedInputStream ("E:\ ready\\ 1.txt"); / / 2. Use stream to read int b; while ((b = in.read ())! =-1) {System.out.println (b);}} catch (Exception e) {e.printStackTrace ();} finally {/ / close stream operation is written in finally {}. Be sure to close it after you finish using it! Try {in.close ();} catch (IOException e) {e.printStackTrace ();} / / this method is used to test the read of byte stream private static void method () {/ / create a local variable that takes effect in this method. Note: initialize InputStream in = null manually. Try {/ / 1. Create byte input stream object to read / / InputStream in = new InputStream (); / / error reason: abstract class cannot be instantiated / / InputStream in = new FileInputStream (new File ("E:\\ ready\\ 1.txt"); in = new FileInputStream ("E:\\ ready\\ 1.txt"); / / 2. Start reading / * read () each call will read a byte. If the end of the data is read, it returns-1 System.out.println / System.out.println (in.read ()); / / System.out.println (in.read ()) / / requirements: all the contents of the file need to be read in a loop until / / variables are defined, and the read data int b; while ((b=in.read ())! =-1) {System.out.println (b);}} catch (Exception e) {e.printStackTrace () / / print the error message / * the third part of the try-catch structure: finally {} * this part is the code that will be executed regardless of whether it catches an exception or not. It is often used to close the stream * /} finally {try {/ / 3. Release resources, stream resources must be released when they are used up! In.close ();} catch (IOException e) {e.printStackTrace ();} 5 character stream read
It is often used to deal with plain text data. Reading and writing are prone to garbled. When reading and writing, it is best to specify the coding set as UTF-8.
5.1 Reader Abstract Class
The abstract class used to read the character stream.
Common methods:
Int read () reads a single character
Int read (char [] cbuf) reads characters into an array
Abstract int read (char [] cbuf, int off, int len) reads characters into some part of the array
Int read (CharBuffer target) attempts to read characters into the specified character buffer
Abstract void close () closes the stream and releases all resources associated with it
5.2 FileReader subclass
A convenient class for reading character files. The constructor of this class assumes that both the default character encoding and the default byte buffer size are appropriate. To specify these values yourself, you can first construct an InputStreamReader on FileInputStream.
Create object
FileReader (String fileName) creates a new FileReader given the file name from which the data is read
FileReader (File file) creates a new FileReader given the File from which the data is read
5.3 BufferedReader subclass
Read text from the character input stream and buffer each character to achieve efficient reading of characters, arrays and lines.
You can specify the size of the buffer, or you can use the default size. In most cases, the default value is large enough.
Create object
BufferedReader (Reader in) creates a buffered character input stream that uses the default size input buffer
5.4 activity: character stream reading case
Create package: cn.tedu.file
Create a class: TestIn2.java
Package cn.tedu.file;import java.io.*;/* this class is used to test character stream reading * / public class TestIn2 {public static void main (String [] args) {/ / method (); / test ordinary character input stream method2 (); / test efficient character input stream} / / create a method for testing efficient character input stream private static void method2 () {/ / 1. Define a local variable that takes effect in this method, and manually initialize the value null Reader in=null; try {/ / 1. Create an efficient character reading stream object / / in = new BufferedReader (new FileReader (new File ("E:\ ready\ 1.txt")); in = new BufferedReader (new FileReader ("E:\ ready\\ 1.txt")); / / 2. Use the stream object int b; while ((b=in.read ())! =-1) {System.out.println (b);}} catch (Exception e) {e.printStackTrace ();} finally {/ / 3. Close the stream object try {in.close ();} catch (IOException e) {e.printStackTrace () Create a method private static void method () {/ / 1.1to test the normal character input stream. Create a local variable that takes effect in this method. Note that the initialization value null Reader in = null Try {/ / 1.2 create character input stream object. Note that you need to catch exception / / Reader in = new Reader (); / / error reason: abstract parent cannot be instantiated / / in = new FileReader ("E:\\ ready\\ 1.txt"); in = new FileReader ("E:\\ ready\\ 1.txt") / / 2. Use the stream object / / System.out.println (in.read ()); / / requirements: read all the contents of the file in a loop, as long as it is not-1, it means there is still data, continue to read / / 3.1define variables, and record the read data int b While (b = in.read ())! =-1) {System.out.println (b);}} catch (Exception e) {e.printStackTrace ();} finally {/ / 3. Try {in.close ();} catch (IOException e) {e.printStackTrace ();} 6 byte flow writes 6.1 OutputStream abstract class
This abstract class is a superclass of all classes that represent the output byte stream. The output stream accepts output bytes and sends them to a receiver.
Common methods:
Void close () closes this output stream and releases all system resources associated with this stream
Void flush () refreshes this output stream and forces all buffered output bytes to be written out
Void write (byte [] b) writes b.length bytes from the specified byte array to this output stream
Void write (byte [] b byte int off, int len) writes the len bytes from the offset off in the specified len array to the output stream
Abstract void write (int b) writes the specified bytes to this output stream
6.2 FileOutputStream subclass
Insert it directly into the file and write out the file data directly
Construction method (create object):
FileOutputStream (String name)
Creates a file output stream that writes data to a file with the specified name
FileOutStream (File file)
Creates a file output stream that writes data to a file represented by a specified File object
FileOutStream (File file,boolean append)-if the second parameter is true, it is appended and not overridden
Creates a file output stream that writes data to the file represented by the specified File object, with the following parameter indicating whether to overwrite the contents of the original file
6.3 BufferedOutputstream subclass
This class implements a buffered output stream, and by setting this output stream, the application can write each byte to the underlying output stream without having to call the underlying system for each byte write.
Construction method (create object):
BufferedOutputStream (OutputStream out)
Creates a new buffered output stream to write data to the specified underlying output stream
6.4 exercise: byte output stream test:
Create package: cn.tedu.file
Create a class: TestOut.java
Package cn.tedu.file;import java.io.*;/* this class is used to test the byte output stream * / public class TestOut {public static void main (String [] args) {method (); / / to test the normal byte output stream / / method2 () / / for testing efficient byte output streams} / / create a method for testing efficient byte output streams private static void method2 () {/ / 1. To create a local variable that takes effect in this method, initialize OutputStream out = null; try {/ / 2 manually. Create an efficient byte output stream object / / out = new BufferedOutputStream (new FileOutputStream (new File ("E:\ ready\\ 2.txt")); out = new BufferedOutputStream (new FileOutputStream ("E:\ ready\\ 2.txt")); / / 3. Use stream objects-write out operations out.write (97);} catch (Exception e) {e.printStackTrace ();} finally {/ / close stream operations to put try {/ / 4 in finally {}. Close the stream out.close ();} catch (IOException e) {e.printStackTrace ();} / / create a method private static void method () {/ / 1 that is used to test the normal byte output stream. To create a local variable that takes effect in this method, initialize null OutputStream out = null; / / 2 manually. Create a try-catch-finally structure because the IO operation may result in an exception try {/ / 3. Create a normal byte output stream object / / out = new FileOutputStream (new File ("E:\ ready\\ 2.txt"); / / out = new FileOutputStream ("E:\ ready\\ 2.txt"); out = new FileOutputStream ("E:\ ready\\ 2.txt", true); / / 4. Use stream objects-- write out out.write (99); / an out.write (99) in the corresponding ASCII code table; / / b out.write (99) in the corresponding ASCII code table; / / c} catch (Exception e) {e.printStackTrace () in the corresponding ASCII code table } finally {/ / if you want the code to be executed, you need to write try {/ / 5 in finally. Out.close ();} catch (IOException e) {e.printStackTrace ();} 7 character streams write 7.1Writer abstract classes
An abstract class that writes a character stream
Common methods:
Abstract void close () closes the stream, but refreshes it first
Void write (char [] cbuf) write character array
Void write (int c) writes a single character
Void write (String str) write string
Void write (String str,int off,int len) writes a portion of a string
Abstract void write (char [] cbuf,int off,int len) writes a portion of the character array
7.2 FileWriter subclass
A convenience class for writing character files, which is constructed on the assumption that both the default character encoding and the default byte buffer size are acceptable. If you need to customize these values yourself, you can first construct an OutputStreamWriter. Exe on FileOutputStream.
Construction method (create object):
FileWriter (String filename)
Construct a FileWriter object based on the given file name
FileWriter (String filename,boolean append)
Construct a FileWriter based on a given file name and a Boolean value indicating whether to append the written data
7.3 BufferedWriter subclass
Write text to the character output stream, buffering individual characters, thus providing efficient writing of individual characters, arrays and strings. You can specify the size of the buffer, or accept the default size, which is large enough in most cases
Construction method (create object):
BufferedWriter (Writer out)
Create a buffered character output stream using the default size output buffer
7.4 exercise: character output stream test:
Create package: cn.tedu.file
Create a class: TestOut2.java
Package cn.tedu.file;import java.io.*;/* this class is used to test the character output stream * / public class TestOut2 {public static void main (String [] args) {/ / method (); / / to test the normal character output stream method2 () / / for testing efficient character output streams} / / create a method for testing efficient character output streams private static void method2 () {/ / 1. Create a local variable that takes effect in this method. The value is null. Initialize it manually! Writer out = null; / / 2. Because the program may throw an exception, you need to write a try-catch-finally structure try {/ / to store the code / / 3 that may throw an exception. Create a normal character output stream object / / out = new BufferedWriter (new FileWriter ("E:\ ready\\ 2.txt")); / / out = new BufferedWriter (new FileWriter ("E:\ ready\\ 2.txt"); out = new BufferedWriter ("E:\ ready\\ 2.txt", true); / / 4. Use stream objects out.write;} catch (Exception e) {/ / match and catch exception e.printStackTrace () / / print an error message if an exception is caught} finally {/ / A block of code to which finally {/ / must be executed, which is often used to close the stream try {out.close ();} catch (IOException e) {e.printStackTrace () Create a method to test the normal character output stream private static void method () {/ / 1. Create a local variable that takes effect in this method. The value is null. Initialize it manually! Writer out = null; / / 2. Because the program may throw an exception, you need to write a try-catch-finally structure try {/ / to store the code / / 3 that may throw an exception. Create a normal character output stream object / / out = new FileWriter (new File ("E:\ ready\\ 2.txt"); / / out = new FileWriter ("E:\ ready\\ 2.txt"); out = new FileWriter ("E:\ ready\\ 2.txt", true); / / 4. Use stream objects out.write (98);} catch (Exception e) {/ / match and catch exception e.printStackTrace () / / print error message if an exception is caught} finally {/ / A block of code to which finally {/ / must be executed, which is often used to close the stream try {out.close ();} catch (IOException e) {e.printStackTrace ();} 8 extension
By learning the above streams, we can also expand and try to copy the following files:
Create package: cn.tedu.file
Create a class: TestCopyFile.java
Package cn.tedu.file;import java.io.*;import java.util.Scanner;/* this class is used to practice file replication synthesis case * / public class TestCopyFile {public static void main (String [] args) {/ / 1. Prompt and receive the two paths System.out.println entered by the user ("please enter the source file path"); / /-- the copied file String f = new Scanner (System.in). NextLine (); System.out.println ("Please enter the new file path:"); / /-- the copied new file String t = new Scanner (System.in). NextLine (); / / 2. Call the custom method created to complete the file copy / / ZFCopy (fmagt); / / use the character stream to complete the file copy case ZJCopy (fPowert); / / use the byte stream to complete the file copy case} / / use the byte flow to complete the file copy case private static void ZJCopy (String f, String t) {/ / 1. Define local variables that take effect throughout the method. Initialize them manually. The default value of the reference type is null InputStream in = null; OutputStream out = null; / / 2. Since exceptions may occur in the code, you need to write the try-catch-finally structure try {/ / 3.1 to create an efficient byte input stream object-- the parameter of FIS is the source file path fin = new BufferedInputStream (new FileInputStream (f)) passed in by the user / / 3.2 create an efficient byte output stream object-the parameter of FOS is the new file path t out = new BufferedOutputStream (new FileOutputStream (t)) passed by the user; / / 4. Complete the business with the created stream object / / 4. 1 define variables to hold the read data int b / / 4.2 read the data in the source file in a loop. As long as it is not-1, the data loop will continue to while ((b = in.read ())! =-1) {/ / 4.3.Writing the read data to the new file out.write (b);} System.out.println ("Congratulations! File copied successfully! ") ;} catch (Exception e) {System.out.println ("Sorry! file copy failed!") ; e.printStackTrace ();} finally {try {out.close ();} catch (IOException e) {e.printStackTrace ();} try {in.close ();} catch (IOException e) {e.printStackTrace () Use character stream to complete file copy case private static void ZFCopy (String f, String t) {/ / 1. Define local variables that take effect throughout the method. Initialize them manually. The default value is null Reader in = null; Writer out = null; / / 2. Since exceptions may occur in the code, you need to write the try-catch-finally structure try {/ / 3.1 to create an efficient character input stream object in = new BufferedReader (new FileReader (f)); / / 3.2 to create an efficient character output stream object out = new BufferedWriter (new FileWriter (t)); / / 4. Once you have the stream object, you can use the stream object to complete the business. / / 4.1.Definitions of variables are used to hold the read data int b / / 4.2 read the source file in a loop until the return value is-1, indicating that there is no data, and then end the loop while ((b=in.read ())! =-1) {/ / 4.3 write the data read in this cycle to the new file out.write (b) } System.out.println ("Congrats! File copied successfully! ") ;} catch (Exception e) {System.out.println ("Sorry! file copy failed!") ; e.printStackTrace ();} finally {/ * flow closure is in order: if there are multiple streams, the last created stream is the first to close * multiple flow closure statements require their own try-catch*/ try {out.close ();} catch (IOException e) {e.printStackTrace () } try {in.close ();} catch (IOException e) {e.printStackTrace ();} 9 Summary: inheritance structure of IO
1. Mainstream classification
Classified by direction: input stream output stream (relative to the program, writing data from the program to the file is output)
Classified by transport type: byte stream character stream
Combination: byte input stream byte output stream character input stream character output stream
two。 Learning methods: learn general methods in abstract parent classes and how to create objects in subclasses
3. Byte input stream:
InputStream abstract class, which cannot be new, can be used as a superclass. Learn the common methods it provides-- FileInputStream subclass, byte input stream for operating files, ordinary class-- BufferedInputStream subclass, buffer byte input stream, general class.
4. Character input stream
Reader abstract class, which cannot be new, can be used as a superclass. Learn the common methods it provides-- FileReader, subclasses, character input streams for manipulating files, ordinary classes-- BufferedReader, subclasses, buffered character input streams, ordinary classes.
5. Byte output stream:
OutputStream abstract class, can not new, can be used as a superclass, learn the common methods it provides-FileOutputStream subclass, operation file byte output stream, ordinary class-BufferedOutputStream subclass, buffer byte output stream, ordinary class
6. Character output stream
Writer abstract class, can not new, can be used as a superclass, learn its common methods-FileWriter, subclass, operation file character output stream, ordinary class-BufferedWriter, subclass, buffer character output stream, ordinary class above is "JAVA IO stream, File, byte flow and character stream instance analysis" all the content of this article, thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
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.