Dark Horse programmer-java basic IO stream-bytes stream buffer and word throttling, javaio

Source: Internet
Author: User

Dark Horse programmer-java basic IO stream-bytes stream buffer and word throttling, javaio


Shard Stream Buffer

L the emergence of a buffer increases the efficiency of reading and writing data.

L corresponding class

• BufferedWriter

• BufferedReader

L the buffer zone can be used only when combined with the stream.

L The streaming function is enhanced based on the stream.

1, BufferedWriter

Each time a row can be written, the buffer zone appears to improve the efficiency of stream operations. Therefore, before creating a buffer, you must first have a stream object. This buffer provides a cross-platform line break, newLine ();

/* The emergence of a buffer is to improve the efficiency of stream operations. Therefore, before creating a buffer, you must first have a stream object. This buffer provides a cross-platform line break. NewLine (); */public class BufferedWriterDemo {public static void main (String [] args) {FileWriter fw = null; BufferedWriter bw = null; try {// create a character to write the stream object. Fw = new FileWriter ("target.txt"); // to improve the efficiency of character writing. Added the buffer technology. // You only need to pass the stream object that needs to be improved as a parameter to the buffer's constructor. bw = new BufferedWriter (fw); for (int x = 1; x <5; x ++) {bw. write ("abcd" + x); bw. newLine (); bw. flush ();} // remember to refresh as long as the buffer zone is used. // Bufw. flush ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {if (bw! = Null) {try {// actually closes the buffer, which is the stream object in the buffer. Bw. close () ;}catch (IOException e) {e. printStackTrace ();}}}}}
2, BufferedReader

The buffer zone provides the readLine Method for reading a row at a time to facilitate the acquisition of text data. If null is returned, it indicates reading the end of the file. When the readLine method returns, only the data content before the carriage return is returned. Carriage return is not returned. */Public class BufferedReaderDemo {public static void main (String [] args) {// TODO Auto-generated method stubFileReader fr = null; BufferedReader br = null; try {// create a stream reading object and file association. Fr = new FileReader ("target.txt"); // to improve efficiency. Add the buffer technology. The constructor that passes the character reading Stream object as a parameter to the buffer object. Br = new BufferedReader (fr); String readLine = null; while (readLine = br. readLine ())! = Null) {System. out. print (readLine) ;}} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {if (br! = Null) {try {br. close ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}}}
3. Copy files through the buffer zone

The principle of the readLine method, whether it is to read a row, get to read multiple characters. In fact, they are all read one by one on the hard disk. Therefore, the read method is used to read one by one.

Public class CopyFileByBuff {public static void main (String [] args) {// TODO Auto-generated method stubBufferedReader br = null; BufferedWriter bw = null; try {br = new BufferedReader (new FileReader ("CopyText. java "); bw = new BufferedWriter (new FileWriter (" targetFile.txt "); String line = null; while (line = br. readLine ())! = Null) {bw. write (line); bw. newLine (); bw. flush () ;}} catch (Exception e) {// TODO Auto-generated catch blockthrow new RuntimeException ("read/write failed");} finally {if (br! = Null) {try {br. close ();} catch (IOException e) {// TODO Auto-generated catch blockthrow new RuntimeException ("read close failed") ;}} if (bw! = Null) {try {bw. close ();} catch (IOException e) {// TODO Auto-generated catch blockthrow new RuntimeException ("Write close failed ");}}}}}
4. Custom Character Buffer

/* After understanding the principle of the special method readLine in the BufferedReader class, you can customize a class that contains a method with the same function as readLine. Simulate BufferedReader */import java. io. *; class MyBufferedReader extends Reader {private Reader r; MyBufferedReader (Reader r) {this. r = r ;}// you can read a row of data at a time. Public String myReadLine () throws IOException {// defines a temporary container. The original BufferReader encapsulates character arrays. // For ease of demonstration. Define a StringBuilder container. Because the data will eventually be converted into a string. StringBuilder sb = new StringBuilder (); int ch = 0; while (ch = r. read ())! =-1) {if (ch = '\ R') continue; if (ch =' \ n') return sb. toString (); elsesb. append (char) ch);} if (sb. length ()! = 0) return sb. toString (); return null;}/* overwrites the abstract method in the Reader class. */Public int read (char [] cbuf, int off, int len) throws IOException {return r. read (cbuf, off, len);} public void close () throws IOException {r. close ();} public void myClose () throws IOException {r. close () ;}} class MyBufferedReaderDemo {public static void main (String [] args) throws IOException {FileReader fr = new FileReader ("buf.txt "); myBufferedReader myBuf = new MyBufferedReader (fr); String line = null; while ((Line = myBuf. myReadLine ())! = Null) {System. out. println (line) ;}mybuf. myClose ();}}
5,

Decoration Design Mode:

When you want to enhance the functions of existing objects, you can define a class to pass in existing objects.

To enhance the function, the custom class is called the decoration class.

Decoration Classes usually receive decorated objects through constructor methods, and provide stronger functions based on the features of decorated objects.

/* Decoration Design Mode: When you want to enhance the functions of existing objects, you can define a class, pass in existing objects, and provide enhanced functions based on existing functions. The custom class is called the decoration class. Decoration Classes usually receive decorated objects through constructor. And provides stronger functions based on the functions of the objects to be decorated. */Public class PersonDemo {public static void main (String [] args) {// TODO Auto-generated method stubPerson p = new Person (); // p. chifan (); SuperPerson sp = new SuperPerson (p); sp. superChifan () ;}} class Person {public void chifan () {System. out. println ("dinner") ;}} class SuperPerson {private Person p; SuperPerson (Person p) {this. p = p;} public void superChifan () {System. out. println ("appealer"); p. chifan (); System. out. println ("dessert"); System. out. println (" ");}}
6. Differences between decoration and inheritance

Pre-optimization system:

MyReader: A class used to read data.

| -- MyTextReader: Read text

| -- MyBufferTextReader: Read text Buffer

| -- MyMediaReader: Read Media

| -- MyBufferMediaReader: Read the media Buffer

| -- MyDataReader: Read data

| -- MyBufferDataReader: Read data buffer

Optimized System:

MyReader: A class used to read data.

| -- MyTextReader: Read text

| -- MyMediaReader: Read Media

| -- MyDataReader: Read data

| -- MyBufferReader: Buffer

The decoration mode is more flexible than inheritance, avoiding the bloated inheritance system and reducing the relationship between classes.

Because of the enhancement of existing objects, the decoration class has the same functions as existing ones, but only provides stronger functions.

Therefore, the decoration class and the decoration class usually belong to a system.

7. Custom Decoration

/* After understanding the principle of the special method readLine in the BufferedReader class, you can customize a class that contains a method with the same function as readLine. Simulate BufferedReader */import java. io. *; class MyBufferedReader extends Reader {private Reader r; MyBufferedReader (Reader r) {this. r = r ;}// you can read a row of data at a time. Public String myReadLine () throws IOException {// defines a temporary container. The original BufferReader encapsulates character arrays. // For ease of demonstration. Define a StringBuilder container. Because the data will eventually be converted into a string. StringBuilder sb = new StringBuilder (); int ch = 0; while (ch = r. read ())! =-1) {if (ch = '\ R') continue; if (ch =' \ n') return sb. toString (); elsesb. append (char) ch);} if (sb. length ()! = 0) return sb. toString (); return null;}/* overwrites the abstract method in the Reader class. */Public int read (char [] cbuf, int off, int len) throws IOException {return r. read (cbuf, off, len);} public void close () throws IOException {r. close ();} public void myClose () throws IOException {r. close () ;}} class MyBufferedReaderDemo {public static void main (String [] args) throws IOException {FileReader fr = new FileReader ("buf.txt "); myBufferedReader myBuf = new MyBufferedReader (fr); String line = null; while ((Line = myBuf. myReadLine ())! = Null) {System. out. println (line) ;}mybuf. myClose ();}}
8. byte stream File read/write operations

/* Upload stream: FileReaderFileWriter. BufferedReaderBufferedWriter byte stream: Required for InputStream OutputStream. You want to operate image data. Byte streams are used. Copy an image. */import java. io. *; class FileStream {public static void main (String [] args) throws IOException {readFile_3 ();} public static void readFile_3 () throws IOException {FileInputStream fiis = new FileInputStream ("fos.txt"); // int num = fiis. available (); byte [] buf = new byte [FCM. available ()]; // defines a buffer that is just right. You don't have to loop. Fiis. read (buf); System. out. println (new String (buf); Sox. close ();} public static void readFile_2 () throws IOException {FileInputStream FD = new FileInputStream ("fos.txt"); byte [] buf = new byte [1024]; int len = 0; while (len = Fi. read (buf ))! =-1) {System. out. println (new String (buf, 0, len);} FCM. close ();} public static void readFile_1 () throws IOException {FileInputStream FD = new FileInputStream ("fos.txt"); int ch = 0; while (ch = FCM. read ())! =-1) {System. out. println (char) ch);} fiis. close ();} public static void writeFile () throws IOException {FileOutputStream fos = new FileOutputStream ("fos.txt"); fos. write ("abcde ". getBytes (); fos. close ();}}
9. Copy an image

/* Copy an image idea: 1. Use bytes to read the stream object and associate the image. 2. Write data into a stream object in bytes to create an image file. Used to store the obtained image data. 3. data is stored Through cyclic read/write. 4. Close the resource. */Public class CopyPic {public static void main (String [] args) {FileInputStream FD = null; FileOutputStream fos = null; try {FD = new FileInputStream ("a.png "); fos = new FileOutputStream ("B .png"); int len = 0; byte [] buff = new byte [1024]; while (len = FCM. read (buff ))! =-1) {fos. write (buff, 0, len); fos. flush () ;}} catch (Exception e) {// TODO: handle exceptionthrow new RuntimeException ("failed to copy image");} finally {if (FS! = Null) {try {FS. close ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace (); throw new RuntimeException ("failed to close reading") ;}} if (fos! = Null) {try {fos. close ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace (); throw new RuntimeException ("Write close failed ");}}}}}
10. byte stream buffer

/* Demonstrate how to copy mp3 files. Through the buffer zone. BufferedOutputStreamBufferedInputStream */import java. io. *; class CopyMp3 {public static void main (String [] args) throws IOException {long start = System. currentTimeMillis (); copy_2 (); long end = System. currentTimeMillis (); System. out. println (end-start) + "millisecond");} public static void copy_2 () throws IOException {MyBufferedInputStream bufd = new MyBufferedInputStream (new FileInputStream ("c: \ 9.mp3 "); BufferedOu TputStream bufos = new BufferedOutputStream (new FileOutputStream ("c: \ 3.mp3"); int by = 0; // System. out. println ("first byte:" + buisi. myRead (); while (by = bufcm. myRead ())! =-1) {bufos. write (by);} bufos. close (); bufas. myClose ();} // The data is copied through the buffer zone of the byte stream. Public static void copy_1 () throws IOException {BufferedInputStream buf_= new BufferedInputStream (new FileInputStream ("c: \ 0.mp3"); writable bufos = new BufferedOutputStream (new FileOutputStream ("c: \ 1.mp3 "); int by = 0; while (by = bufcm. read ())! =-1) {bufos. write (by);} bufos. close (); bufcm. close ();}}
11. Read keyboard input

/* Read the keyboard entry. System. out: corresponds to the standard output device, console. System. in: The corresponding standard input device: keyboard. Requirement: enter data through the keyboard. After a row of data is input, the row of data is printed. If the input data is over, the input is stopped. */Import java. io. *; class ReadIn {public static void main (String [] args) throws IOException {InputStream in = System. in; StringBuilder sb = new StringBuilder (); while (true) {int ch = in. read (); if (ch = '\ R') continue; if (ch =' \ n') {String s = sb. toString (); if ("over ". equals (s) break; System. out. println (s. toUpperCase (); sb. delete (0, sb. length ();} elsesb. append (char) ch );}}}
12. Read and Write the conversion stream

/*
By inputting a row of data on the keyboard and printing it in uppercase, we can see that it is actually the principle of reading a row of data. That is, the readLine method. Can I directly use the readLine method to read a row of data input by the keyboard? The readLine method is the method in the BufferedReader class of the bytes stream. The read method entered by the keyboard is the byte stream InputStream method. So can we convert byte streams into the readLine method that uses the swap stream buffer? */Import java. io. *; class TransStreamDemo {public static void main (String [] args) throws IOException {// obtain the keyboard input object. // InputStream in = System. in; // convert a byte stream object to a bytes Stream object and use the conversion stream. InputStreamReader // InputStreamReader isr = new InputStreamReader (in); // the string is used for highly efficient buffer operations to improve efficiency. Use BufferedReader // BufferedReader bufr = new BufferedReader (isr); // the most common method of writing a keyboard. BufferedReader bufr = new BufferedReader (new InputStreamReader (System. in); // OutputStream out = System. out; // OutputStreamWriter osw = new OutputStreamWriter (out); // BufferedWriter bufw = new BufferedWriter (osw); 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 ();}}
13. stream operation rules

1. Source: Enter the keyboard. Purpose: To log on to the console. 2. Requirement: store the data entered by the keyboard into a file. Source: keyboard. Purpose: file. 3. Requirement: print the data of a file on the console. Source: file. Purpose: To log on to the console. The basic rule of stream operations: the most painful thing is that there are many stream objects and you don't know which one to use. It can be accomplished through three definitions. 1. Clarify the source and purpose. Source: input stream. InputStream Reader objective: to output a stream. OutputStream Writer. 2. Whether the operated data is plain text. Yes: streams. No: byte stream. 3. When the system is clear, specify the specific object to use. Distinguish between devices: Source Device: memory, hard disk. Target keyboard devices: memory, hard disk, and console. 1. store data in one text file to another. Copy a file. Source: because it is the source, the read stream is used. Whether InputStream Reader operates text files. Yes! In this case, you can choose Reader. Next, specify the object in the system. Device: hard disk. The previous file. In the Reader system, the object that can operate files is whether FileReader needs to improve efficiency: Yes !. In the Reader system, buffer BufferedReader. FileReader fr = new FileReader ("a.txt"); BufferedReader bufr = new BufferedReader (fr); Objective: whether OutputStream Writer is plain text. Yes! Writer. Device: hard disk, a file. The object FileWriter that can operate files in the Writer system. Whether to improve efficiency: Yes !. Add the buffer BufferedWriterFileWriter fw = new FileWriter ("B .txt") in the Writer system; BufferedWriter bufw = new BufferedWriter (fw); exercise: store data in one image file to another. Copy a file. You must complete the three definitions in the preceding format. ------------------------------------- 2. Requirement: Save the data entered by the keyboard to a file. Both sources and purposes exist in this requirement. Then analyze the source separately: Is InputStream Reader plain text? Yes! Reader device: keyboard. The corresponding object is System. in. Didn't you select Reader? Does System. in correspond to a byte stream? To facilitate the operation of text data on the keyboard. It is most convenient to convert a stream into a string. Therefore, since Reader is clearly defined, System. in is converted to Reader. Using the Reader System to convert the stream, InputStreamReaderInputStreamReader isr = new InputStreamReader (System. in); do you need to improve the efficiency? Yes! BufferedReaderBufferedReader bufr = new BufferedReader (isr); Objective: Does OutputStream Writer store text? Yes! Writer. Device: hard disk. One file. Use FileWriter. FileWriter fw = new FileWriter ("c.txt"); do you need to improve efficiency? Yes. BufferedWriter bufw = new BufferedWriter (fw); **************** to extend the input data according to the specified encoding table (UTF-8 ), store data in a file. Objective: Does OutputStream Writer store text? Yes! Writer. Device: hard disk. One file. Use FileWriter. However, FileWriter uses the default encoding table. GBK. But during storage, you need to add the specified encoding table UTF-8. The specified encoding table can only be specified for the conversion stream. Therefore, the object to be used is OutputStreamWriter. The conversion Stream object must receive a byte output stream. It can also operate the byte output stream of files. FileOutputStreamOutputStreamWriter osw = new OutputStreamWriter (new FileOutputStream ("d.txt"), "UTF-8"); need efficiency? Yes. BufferedWriter bufw = new BufferedWriter (osw); so remember. What is the usage of the conversion stream. A bridge between characters and bytes. Generally, a conversion stream is required when character encoding is involved.
/* Exercise: print a text data file on the console. You must complete the three definitions in the preceding format. */Class TransStreamDemo2 {public static void main (String [] args) throws IOException {System. setIn (new FileInputStream ("PersonDemo. java "); System. setOut (new PrintStream ("zzz.txt"); // The most common keyboard writing method. BufferedReader bufr = new BufferedReader (new InputStreamReader (System. in); 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 ();}}
14. Change the standard input/output device
Class TransStreamDemo2 {public static void main (String [] args) throws IOException {System. setIn (new FileInputStream ("PersonDemo. java "); System. setOut (new PrintStream ("zzz.txt"); // The most common keyboard writing method. BufferedReader bufr = new BufferedReader (new InputStreamReader (System. in); 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 ();}}
15. Abnormal log information

Import java. io. *; import java. util. *; import java. text. *; class ExceptionInfo {public static void main (String [] args) throws IOException {try {int [] arr = new int [2]; System. out. println (arr [3]);} catch (Exception e) {try {Date d = new Date (); SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss "); String s = sdf. format (d); PrintStream ps = new PrintStream ("exeception. log "); ps. println (s); System. setOut (ps);} catch (IOException ex) {throw new RuntimeException ("log file creation failed");} e. printStackTrace (System. out );}}}
16. Obtain system information

import java.util.*;import java.io.*;class  SystemInfo{public static void main(String[] args) throws IOException{Properties prop = System.getProperties();//System.out.println(prop);prop.list(new PrintStream("sysinfo.txt"));}}


















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: info-contact@alibabacloud.com 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.