Black Horse programmer _ other stream learning notes in the JAVA input/output system

Source: Internet
Author: User

1. byte array stream

The byte array stream class can operate on the byte array in memory. Its data is a byte array. The adapter design mode of the byte array stream class. It converts the byte array type to the stream type so that the program can read and write the byte array.

1. ByteArrayInputStream class

ByteArrayInputStream reads data from the byte array in the memory. Its data is a byte array. ByteArrayInputStream adapter design mode, which converts the byte array type to the input stream type so that the program can read the byte array.

The following is the sample code:

Public class ByteArrayInputStreamDemo {public static void main (String args []) throws IOException {readByteArrayStream ();} /***** ByteArrayInputStream Method for reading byte arrays * @ throws IOException */public static void readByteArrayStream () throws IOException {String str = "zhisytoitheima"; byte [] strBuf = str. getBytes (); ByteArrayInputStream baiS = new ByteArrayInputStream (strBuf); int data = baiS. read (); while (data! =-1) {char upper = Character. toUpperCase (char) data); System. out. print (upper + ""); data = baiS. read ();} baiS. close ();}}

The running result is as follows:

2. ByteArrayOutputStream class

ByteArrayOutputStream writes data to the byte array in the memory. Its data is a byte array. ByteArrayOutputStream adapter design mode, which converts the byte array type to the output stream type so that the program can write the byte array.

The ByteArrayOutputStream class is constructed as follows:

ByteArrayOutputStream (): Creates a new byte array output stream. The buffer initially contains 32 bytes, which can be increased if necessary.

ByteArrayOutputStream (int size): Creates a new byte array output stream that has a specified buffer capacity in bytes.

Sample Code:

1/** 2 * convert the string to a byte array and write it to the byte array output stream. 3 * @ author branch: Shengyong 4*5 */6 public class ByteArrayOutputStreamDemo {7 8 public static void main (String args []) throws IOException {9 10 writeByteArrayStream (); 11} 12 13 14/*** 15 * ByteArrayInputStream Method 16 * @ throws IOException17 */18 public static void writeByteArrayStream () throws IOException {19 20 String str = "zhisytoitheimatestByteArrayInputStream"; 21 byte [] strBuf = str. getBytes (); 22 ByteArrayOutputStream baoS = new ByteArrayOutputStream (512); 23 24 baoS. write (strBuf); // write the bytes in the specified byte array to the baoS byte array and output the 25 System. out. println (baoS. toString (). toUpperCase (); // convert the buffer content to a string by decoding bytes and output 26 27 // create a new byte array for the row, and copy the content of the byte array output stream to the array 28 byte [] newStrBuf = baoS. toByteArray (); 29 for (int I = 0; I <newStrBuf. length; I ++) {30 System. out. print (char) newStrBuf [I]); 31} 32 33} 34}

Ii. Pipeline Flow

A PipedInputStream object must be connected to a PipedOutputStream object to generate a communication pipeline. PipedOutputStream can write data to the pipeline. Generally, one thread writes data to the output stream of the pipeline, and the other thread reads data from the input stream of the pipeline. PipedInputStream can read the data written by PipedOutputStream from the pipeline. These two classes are mainly used to complete the communication between threads. When thread A executes the read () method of the pipeline input stream, if there is no data at the moment, the thread will be blocked, only when thread B returns new data to the MPs queue, will thread A be re-executed.

Sample Code:

1/** 2 * Thread for writing data to the output stream of the pipeline 3 */4 class MyWriter extends Thread {5 6 private PipedOutputStream out = new PipedOutputStream (); 7 private String content = ""; 8 9 public MyWriter (String content) {10 11 this. content = content; 12} 13 14 15 public PipedOutputStream getOut () {16 return out; 17} 18 19 @ Override20 public void run () {21 // TODO Auto-generated method stub22 super. run (); 23 try {24 System. out. println (""); 25 out. write (content. getBytes (); 26 out. close (); 27 System. out. println (""); 28} catch (Exception e) {29 30 throw new RuntimeException (e ); 31} 32} 33 34} 35 36 37/*** 38 * read data from the pipeline input stream 39 */40 public class PipedStreamDemo extends Thread {41 42 private PipedInputStream in; 43 44 public PipedStreamDemo (MyWriter out) throws IOException {45 46 this. in = new PipedInputStream (); 47 in. connect (out. getOut (); // connects the output stream of the pipeline. And MPs queue input stream 48} 49 50 51 @ Override52 public void run () {53 // TODO Auto-generated method stub54 super. run (); 55 56 try {57 byte [] buf = new byte [1024]; 58 int len = 0; 59 String readStr = ""; 60 System. out. println (""); 61 while (len = in. read (buf ))! =-1) {62 63 readStr + = new String (buf, 0, len); 64} 65 System. out. println (readStr); 66 in. close (); 67 System. out. println (""); 68} catch (Exception e) {69 70 throw new RuntimeException (e); 71} 72} 73 74 75 public static void main (String args []) throws IOException {76 77 MyWriter myW = new MyWriter ("I think of dark horse! "); 78 79 PipedStreamDemo myR = new PipedStreamDemo (myW); 80 myW. start (); 81 myR. start (); 82} 83 84}

Iii. Random access to files

In Java, an Object in the RandomAccessFile class provides support for random read/write files. It does not inherit InputStream and OutputStream, but directly inherits the Object, the interfaces DataInput and DataOutput are also implemented. To generate a RandomAccessFile object, you must specify the read/write mode in addition to the file object or file name. For example, the following statement:

RandomAccessFile raf = new RandomAccessFile ("E: \ yy. dat", "r"); random read operation on file E: \ yy. dat

RandomAccessFile raf = new RandomAccessFile ("E: \ yy1.dat", "rw"); random read/write operations on file E: \ yy1.dat

Java random read/write byte files can be viewed as a large byte array, and random read/write operations can be viewed as "virtual byte array, the subscript of this "array" is the so-called file pointer. Therefore, the first operation for random file reading/writing is to move the file pointer. The operations include the following:

Long getFilePointer (): pointer position of the current file.

Void seek (long pos): moves the file pointer to the specified position, and calculates the position from 0.

Int skipBytes (int n): moves the object pointer to the end of the object to the specified n Bytes. The number of actually moved bytes is returned. If n is less than 0, no movement is performed.

Sample Code:

1/*** write 10 double real numbers to the e: \ yy.txt file, then, use RandomAccessFile to randomly modify the data 3 * @ author branch Shengyong 4*5 */6 public class RandomRWDemo {7 8 9 public static void main (String [] args) throws IOException {10 11 randomWrite ("E: \ yy. dat "); 12 13 randomModify (" E: \ yy. dat "); 14} 15 16 17/*** 18 * write data to the file 19 * @ param fileName20 * @ throws IOException21 */22 public static void randomWrite (String fileName) throws IOException {23 24 File file = new File (fileName); 25 if (! File. exists () {26 27 file. createNewFile (); 28} 29 30 if (! File. isFile () {// if it is not a file, 31 32 System is returned. out. print ("not a file"); 33 return; 34} 35 36 37 38 RandomAccessFile aWFile = new RandomAccessFile (file, "rw"); 39 int I = 1; 40 while (I <= 10) {41 aWFile. writeDouble (I); // write the doubl value 42 System. out. print ("" + (double) I); 43 I ++; 44} 45 aWFile. close (); 46} 47 48 49 public static void randomModify (String fileName) throws IOException {50 51 final int DOUBLE_SIZE = 8; // double type occupies 8 bytes 52 File f Ile = new File (fileName); 53 if (! File. exists () {54 System. out. println ("the file to be modified does not exist"); 55 return; 56} 57 58 if (! File. isFile () {59 System. out. println ("not a file"); 60 return; 61} 62 63 RandomAccessFile aMFile = new RandomAccessFile (file, "rw"); 64 65 aMFile. seek (2 * DOUBLE_SIZE); // modify 2nd double values 66 aMFile. writeDouble (100); 67 68 aMFile. seek (7 * DOUBLE_SIZE); // modify 7th double values 69 aMFile. writeDouble (200); 70 71 aMFile. close (); 72 73 // check if 74 75 RandomAccessFile aRFile = new RandomAccessFile (file, "r"); 76 System. out. println (); 77 for (int I = 0; I <10; I ++) {78 System. out. print ("" + aRFile. readDouble (); 79} 80 aRFile. close (); 81} 82 83}

Running result:

Related Article

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.