Java Learning Diary NUM10

Source: Internet
Author: User

Learning content : In Javaio, it is more important to have five classes, one interface. The five classes are Reaer, Writer,inputstream, Outputstream,file (the first four classes are abstract classes, the last non-abstract), and the interfaces are Serializable. Other stream objects.

one, character streams and byte streamIO streams are used to handle data transfer between devices, and Java is used to manipulate the flow of objects in the IO package. The character stream is based on the stream of characters, which is fused with the text encoding table, so the character stream generally operates the plaintext data, and the byte stream can manipulate all the data. The two base classes of a character stream are reader,writer. The two base classes for a byte stream are InputStream and outputstream. (a) WriterFileWriter1, requirements: Create a file on the hard disk and write the data. Creates a FileWriter object that must be explicitly manipulated when initialized. When you create a FileWriter object, you can pass either the file object or the name of the string type. If a file exists on the hard disk, it will be overwritten and will not be created by itself. If you do not want to be overwritten, you can pass a Boolean value truefilewriter FW = new FileWriter ("Test.txt") in the FileWriter constructor method;//Call the Write method to write the string to the stream. Fw. Writer ("ABCD");//Flushes the stream object's buffer data to the destination Fw.flush (),//closes the stream object, frees the resource when the stream resource is closed, automatically refreshes the internal buffer data, and brushes the data to the destination Fw.close (); BufferedWriter1, requirements: Use BufferedWriter to write data to the hard disk for bufferedwriter, you can increase the efficiency of filewriter because of the buffering technology. Buffer to remember to refresh//Create stream object FileWriter fw = new FileWriter ("Buf.txt");//improve character writing efficiency, introduce buffer technology bufferedwriter BFW = new BufferedWriter (FW) ; Bufw.write ("Hello,heima"); Bufw.flush ();//the Buffer Bufw.close () is flushed/closed as long as the buffer is used; (ii) ReaderCreate a file to read the stream object and specify the name of the file associated, to ensure that the file is already present, if it does not exist, an exception will occur FileReader fr= new FileReader ("Test.txt");//Call the Read method that reads the stream object. Read reads only one character at a time and automatically reads it down. In addition, the Read method has an overloaded form that can read multiple characters at a time, storing multiple characters read in a character array int ch = 0;while ((Ch=read ())!=-1)System.out.println ((char) ch);Close stream Resource fr.close (); The BufferedReader character stream buffer provides a way to read one line at a time, ReadLine (), which gets the text data and, when NULL is returned, reads to the end of the file. Create a read stream object and file associated FileReader fr = new FileReader ("Bufr.txt");//introduce Bufferedreaderbufferedreader BUFR = new for increased efficiency BufferedReader (BUFR); Read operation string line = Null;while (line = Bufr.readline ())!=null) {System.out.println (line);} Close flow bufr.close (); (c) OutputStreamFileOutputStream Requirements: Write data to the hard disk via fileoutputstream fileoutputstream fos = new FileOutputStream ("Fos.txt"); Fos.write (" ABCDE ". GetBytes ()); Fos.close (); (d) InputStreamRequirement: Read a file via FileInputStream and print on console 1, read one byte at a time fileinputstream fis = new FileInputStream ("Fos.txt"); int ch = 0;while (( ch = read ())!=-1) System.out.println ((char) ch); Fis.close (); 2, each read byte is deposited into a byte array fileinputstream fis = new FileInputStream ("Fos.txt"); int len = 0;byte[] buf = new Byte[1024];while (( (BUF))!=-1) System.out.println (New String (buf,0, Len)); Fis.close (); 3, read once, and put the read data into the just good array, which is generally not recommended, because if the data is too large, it will cause memory overflow. Available () method, byte stream-specific FileInputStream FIS = new FileInputStream (); byte[] buf = new byte[fis.available ()]; System.out.println (New String (BUF)); Fis.close (); (v), conversion stream InputStreamReader OutputStreamWriterThe conversion stream is a bridge requirement for byte flow to character streams: the data entered by the keyboard is printed on the console via the conversion stream, ending with over bufferedreader bufr = new BufferedReader (New InputStreamReader (; BufferedWriter BUFW = new BufferedWriter (new OutputStreamWriter (System.out)); String line = Null;while ((Line=bufr.readline ())!=null) {if (' over '. Equals (line)) Break;bufw.write (Line.touppercase () ); Bufw.newline (); Bufw.flush ();} Bufr.close (); (vi), flow operation LawFlow operation of the Basic Law, generally through three clear to complete 1, clear source and destination source: input streamInputStream ReaderPurpose: Output stream OutputStream Writer2, whether the operation of the data is plain text is: Character stream no: byte stream 3, when the system is clear, in the clear to use that specific object through the device to differentiate the source device: memory, hard disk, keyboard purpose device: Memory hard disk, console Two, File (a) Common methods of the file class:1, create. Boolean CreateNewFile (): Creates a file at the specified location, if the file already exists, is not created, and returns false. Unlike the output stream, an output stream object is created to create the file. And the file already exists and will be overwritten. Boolean mkdir (): Creates a folder. Boolean mkdirs (): Creates a multilevel folder. 2, delete. Boolean Delete (): Delete failed to return false. If the file is being used, it cannot be returned to Falsel.  void Deleteonexit (); Deletes the specified file when the program exits. 3, Judge. Boolean exists (): whether the file exists. Isfile (): Isdirectory (); Ishidden (); Isabsolute (); 4. Get the information. GetName (): GetPath (): GetParent (): GetAbsolutePath () long lastmodified () long Length () (ii) a comprehensive case of fileRequirements: Lists the files or folders in the specified directory, including the contents of subdirectories. This is the list of all content in the specified directory. Import*;import java.util.*;class javalistdemo{public static void Main (string[] args) {file dir = new file ("E:\\po Ssible "); list<file> list = new arraylist<file> (); File F = new file (dir, "JavaList.txt"); Filetolist (dir,list); Listtofile (List,f.getabsolutepath ());} public static void Filetolist (file dir,list<file> List) {file[] files = Dir.listfiles (), for (file f:files) {if ( F.isdirectory ()) filetolist (f,list); ElseIf (F.tostring (). EndsWith (". Java")) List.add (f);}} public static void Listtofile (list<file> list,string name) {BufferedWriter BFW = NULL;TRY{BFW = new BufferedWriter (n EW FileWriter (name)); for (File f:list) {bfw.write (F.getabsolutepath ()); Bfw.newline (); Bfw.flush ();}} catch (IOException e) {e.printstacktrace ();} Finally{try{if (Bfw!=null) Bfw.close ();} catch (IOException e) {e.printstacktrace ();}}}} third, some important flow objects 1,propertiesProperties is a subclass of Hashtable, which means that it has the characteristics of a map set and that the key-value pairs stored in it are strings. is a combined container of IO technology in the collection. Important methods Inside: SetProperty (); store (); load (); list (); wait. 2, Print streamPrintWriter PrintStream This stream provides a printing method that can print data of various data types as-is. The PrintStream constructor can receive parameters of type file object string path and byte output stream PrintWriter constructor can receive parameter type file object string path and byte output stream character output stream 3, merging flow SequenceinputstreamThe merge Stream Sequenceinputstream constructor receives a parameter that is an enumeration type. The stream object to be merged is stored in the enumeration and then merged into a stream through the Sequenceinputstream object 4, serialization or persistence of objects SerializableWhen an object is serialized, a UID is customized based on the member, but if the member of the class changes, the stored object cannot be used if the non-static member variable does not want to serialize, precede with the transient keyword, so that it exists in memory, but not in the file note: Static is not able to serialize , you can serialize only the memory- 5, pipe flow pipedinputstream PipedOutputStream The input and output can be connected directly, usually in conjunction with threads. It is not recommended to use a single thread for both objects because deadlocks are prone to occur. 6,randomaccessfile This object can be read or writtenRandom access files are supported for reading and writing to random-access files. This class is not considered a subclass of the IO system, but is inherited directly from object. But it is a member of the IO package because he has the ability to read and write. She encapsulates an array internally, and by manipulating the elements of a pointer array, you can get the pointer position through the Getfilepointer object, and you can change the position of the pointer by seek, or you can only jump forward and read and write through the Sikpbytes (). 7,datastreamObject used to manipulate the base data type 8,arraystreamBytearrayinputstream: You need to receive a data source when constructing, and the data source is an array. Bytearrayoutputstream: At the time of construction, there is no need to define the data purpose, because the object already encapsulates a variable-length byte array, which is the array purpose because both stream objects operate an array, and no system resources are used, so close is not closed.

Java Learning Diary NUM10

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.