The main content

1. Coding problems

2. Use of the File class

3. The use of RandomAccessFile

4.I/O input and output streams

Coding problems:


1 import java.io.UnsupportedEncodingException; 4 public static void main(String[] args) {5 public static void main(String[] args) {5 public static void main(String[] args) {5 public static void main(String[] args) {5 public static void main(String[] args) {5 public static void main(String[] args) { 7 byte[] byte1 = s.getBytes(); GBK 8 for (byte b: 10 System.out.print(integer.tohexString (b & 0xff) + ""); 16 byte[] bytes1 = s.get_bytes (" GBK "); 16 byte[] bytes1 = s.get_bytes (" GBK "); 17 System.out.println(new String(bytes1)); 18 } catch (UnsupportedEncodingException e) { 19 // TODO Auto-generated catch block 20 e.printStackTrace(); 21} 22 /** 23 * GBK encoding: Two bytes for Chinese, one byte for English utF-8 encoding: three bytes for Chinese, one byte for English 24 * Java is double byte encoding, utF-16BE encoding: Chinese takes up two bytes, English takes up two bytes 25 * When your byte sequence is some kind of encoding, and you want to turn the byte sequence into a string, you also need to use this encoding, Otherwise, garbled characters 26 */ 27 try {28 byte[] byte2 = s.gettbytes (" utF-16be "); 29 String s2 = new String(byte2, "utf-16be"); 30 System.out.println(s2); 31 } catch (UnsupportedEncodingException e) { 32 // TODO Auto-generated catch block 33 e.printStackTrace(); 37 * If we create a text file directly on a Chinese machine, This file only knows the ANSI code (e.g., creating a text file directly on the computer). 38 */ 39 40 /** 41 * byte to int is the correct answer. 42 * First, binary in Java is in the form of complement, not source code or inverse code, these three concepts need to be clear; 43 * Second, byte takes 8 bits, and int takes 32 bits. When converting byte to int, if the operation of &44 * 0xFF is not performed and the corresponding byte value is negative, the highest 3 bytes will be filled, which may cause the error of filling. 45 * For example, the byte -1, whose binary (complement) is 11111111 (0xFF), is converted to an int, which should also be -1, but after the complement, 46 * get binary for 11111111111111111111111111111111 (0 XFFFFFFFF), it is not 1, right? 47 * and 0xFF is an int by default, so a byte that matches 0xFF will convert that byte to an int first. In this way, the highest three bytes in the result will always be cleared 0, 48 * and the result will be what we want.Copy the code

Using the File class:


1 import java.io.File; 2 import java.io.IOException; 4 4 public class FileDemo {5 6 /** 7 * @param args 8 */ 9 public static void main(String[] args) {10 ALT+/ 11 File File = new File("E:\ javaio\ imooc"); 13 // system.out.println (file.exists()); 14 if (! file.exists()) 15 file.mkdir(); Mkdirs () if the file does not exist, create folder 16 // mkdir level 1 directory. If you want to create a multi-level directory, use mkdirs() 17 else 18 file.delete(); 21 System.out.println(file.isdirectory ()); 21 System.out.println(file.isdirectory ()); 23 System.out.println(file.isfile ()); 24 25 // File file2 = new File("e:\ javaio\ diary 1.txt"); 26 File file2 = new File("e:\\javaio", "diary 1.txt"); 27 if (! file2.exists()) 28 try { 29 file2.createNewFile(); 30 } catch (IOException e) { 31 // TODO Auto-generated catch block 32 e.printStackTrace(); 33 } 34 else 35 file2.delete(); 37 System.out.println(File); 38 System.out.println(file.getabsolutePath ()); 39 System.out.println(file.getName()); 40 System.out.println(file2.getName()); 41 System.out.println(file.getParent()); 42 System.out.println(file2.getParent()); 43 System.out.println(file.getParentFile().getAbsolutePath()); 44} 45 46}Copy the code

Directory traversal


1 import java.io.File; 2 import java.io.IOException; 4 // List some common operations on File such as filtering, 5 Public class FileUtils {6 /** 7 * Lists all files in the specified directory (including its subdirectories) 8 * 9 * @param dir 10 * @throws IOException 11 */ 12 public static void listDirectory(File dir) throws IOException { 13 if (! Dir.exists ()) {14 throw new IllegalArgumentException(" directory :" + dir + "does not exist "); 15 } 16 if (! Dir. IsDirectory ()) {17 throw new IllegalArgumentException(dir + "not a directory "); 18 } 19 20 // String[] fileNames = 21 // dir.list(); The list() method is used to list the subdirectories and files in the current directory. The name of the subdirectory does not include the contents of the subdirectory. fileNames) { 23 // System.out.println(dir+"\\"+string); 27 File[] files = dir.listFiles(); 27 File[] files = dir.listfiles (); // Returns an abstraction of the direct subdirectory (file) 28 if (files! = null && files.length > 0) {// Determine subdirectory 29 for (File File: Files) {30 if (file.isDirectory()) {31 // recursion32 listDirectory(file); 33 } else { 34 System.out.println(file); 35} 36} 37} 38} 39}Copy the code

The use of RandomAccessFile


1 import java.io.File; 2 import java.io.IOException; 3 import java.io.RandomAccessFile; 4 import java.util.Arrays; 5 6 public class RafDemo { 7 8 /** 9 * @param args 10 */ 11 public static void main(String[] args) throws IOException { 12 File demo = new File("demo"); 13 if (! demo.exists()) 14 demo.mkdir(); 15 File file = new File(demo, "raf.dat"); 16 if (! file.exists()) 17 file.createNewFile(); 18 19 RandomAccessFile raf = new RandomAccessFile(file, "rw"); System.out.println(raf.getFilePointer()); 22 23 raf.write('A'); 24 System.out.println(raf.getFilePointer()); 25 raf.write('B'); 26 27 int i = 0x7fffffff; 29 raf.write(I >>> 24); 29 raf.write(I >>> 24); // high 8 bit 30 raf.write(I >>> 16); 31 raf.write(i >>> 8); 32 raf.write(i); 33 System.out.println(raf.getFilePointer()); 34 34 // Write an int 36 raf. WriteInt (I); 37 38 String s = "middle "; 39 byte[] gbk = s.getBytes("gbk"); 40 raf.write(gbk); 41 System.out.println(raf.length()); 44 raf.seek(0); 46 byte[] buf = new byte[(int) raf.length()]; 46 byte[] buf = new byte[(int) raf.length()]; 47 raf.read(buf); 48 49 System.out.println(Arrays.toString(buf)); 50 for (byte b : buf) { 51 System.out.println(Integer.toHexString(b & 0xff) + " "); 52 } 53 raf.close(); 54} 55 56}Copy the code


import java.io.IOException; import java.io.RandomAccessFile; public class RafReadDemo { /** * @param args */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub RandomAccessFile raf = new RandomAccessFile("demo/raf.dat", "r"); raf.seek(2); int i = 0; int b = raf.read(); // read a byte system.out.println (raf.getFilePointer()); i = i | (b << 24); b = raf.read(); i = i | (b << 16); b = raf.read(); i = i | (b << 8); b = raf.read(); i = i | b; System.out.println(Integer.toHexString(i)); raf.seek(2); i = raf.readInt(); System.out.println(Integer.toHexString(i)); raf.close(); }}Copy the code


1 import java.io.File; 2 import java.io.IOException; 3 import java.io.RandomAccessFile; 4 public class RandomAccessFileSeriaDemo { 5 6 /** 7 * @param args 8 */ 9 public static void main(String[] args) throws IOException { 10 // TODO Auto-generated method stub 11 File demo = new File("demo1"); 12 if (! demo.exists()) 13 demo.mkdir(); 14 File file = new File(demo, "raf.dat"); 15 if (! file.exists()) 16 file.createNewFile(); 18 RandomAccessFile raf = new RandomAccessFile(file, "rw"); 19 /* serialized */ 20 int I = 0x7ffFFFF; 21 raf.write(i >>> 24); 22 raf.write(i >>> 16); 23 raf.write(i >>> 8); 24 raf.write(i); 25 System.out.println(raf.getFilePointer()); 27 /* deserialize */ 28 raf.seek(0); 29 int b = raf.read(); 30 i = i | (b << 24); 31 b = raf.read(); 32 i = i | (b << 16); 33 b = raf.read(); 34 i = i | (b << 8); 35 b = raf.read(); 36 i = i | b; 37 System.out.println(Integer.toHexString(i)); 38 raf.close(); 39 } 40 } 41 42 RandomAccessFileSeriaDemoCopy the code

I/O input and output streams

Definition of a stream:

A stream is a data transfer pipe between a program and a device. There are many buttons on this pipe, and different buttons can perform different functions.

The pipeline for data transmission is a stream, and a stream is a pipeline

On input, the program opens a stream on the source (file, network, memory) and then reads it one by one as shown in the diagram. Same thing with writing.

Classification and use of streams:

Four basic abstract streams: file stream, buffer stream, conversion stream, data stream, Print stream, Object stream.

The java.io package defines multiple stream types (classes or abstract classes) to implement input/output functionality; It can be classified from different angles:

* According to the direction of data flow, it can be divided into input flow and output flow

* Can be divided into byte streams and character streams according to the unit of data processed

* It can be divided into node flow and processing flow according to different functions

All of the stream types provided in JAVA are in package java.io and are derived from the following four abstract stream types:

Node flow and processing flow:

A node stream can read data from a specific data source (node) (e.g., file, memory)

Processing streams are “connected” to existing streams (node streams or processing streams) to provide more powerful read and write capabilities for programs through processing of data.

A node flow is also called a primitive flow and a processing flow is also called a wrap flow.

 

The relationship between streams and classes:

If a class is used to transfer data between a device and a program, the class has a new name called stream

A stream must be a class, but a class need not be a stream

 

An introduction to the four basic flows

Input stream, output stream, byte stream, character stream

InputStream and OutputStream read and write data in one byte

The unit of a Reader and Writer is a character

In JAVA, a character is two bytes

InputStream, OutputStream, Reader, and Writer are all abstract classes, or abstract streams, and we usually use their subclasses. Anything that ends in Stream is a byte Stream.

 

Common methods in InputStream:

 

 

Common methods in OutputStream:

 

Common methods in Reader streams:

 

Common methods in Writer flow:

 

 

File stream

File streams include:

FileInputStream FileOutputStream — a byte stream

FileReader FileWriter — character stream

Example: Read the contents of a file and output it to the monitor, counting the number of bytes read


1 /* 2 Use the FileReader stream to read the data in a file and output it on the monitor! 3 */ 4 5 import java.io.*; 6 7 public class TestFileReader { 8 public static void main(String[] args) { 9 FileReader fr = null; 10 11 try {12 fr = new FileReader("C:\ Documents and Settings\\ Others \\ desktop \\ Java \TestFileReader "); 13 int cnt = 0; 14 int ch; 15 16 while (-1 ! = (ch = fr.read())) // 20 line 17 {18 system.out. print((char) ch); // System.out.print(int ch); 20 ++ CNT; 20 ++ CNT; 20 ++ CNT; Printf (" read %d characters from testFilereader.java ", CNT); 24} catch (FileNotFoundException e) {25 system.out.println (" no file found!" ); 26 System.exit(-1); 27} catch (IOException e) {28 system.out.println (" file read failed!" ); 29 System.exit(-1); 30} 31} 32}Copy the code

 

The use of a FileInputStream

 

The use of FileReader

The difference between byte stream and character stream:

FileInputStream and FileOutputStream can copy files of all formats

FileReader and FileWriter can only copy text files, but cannot copy files of other formats

Since bytes do not need to be decoded and encoded, converting bytes to characters presents decoding and encoding problems

Byte streams can read and write data from devices in all formats, but character streams can only read and write data from devices in text format

Example: programming to achieve file copy


1 /* 2 With FileInputStream and FileOutputStream it is possible to assign 3 to all file formats because bytes are not decoded and encoded, 5 */ 6 7 import java.io.*; 8 9 public class TestFileInputStreamOutputStreamCopy { 10 public static void main(String[] args) { 11 FileInputStream fi  = null; 12 FileOutputStream fo = null; 13 13 try {15 fi = new FileInputStream("E:\\ \\ \\ \\ \\ \ mp3"); 16 fo = new FileOutputStream("d:/share/Output.txt"); 17 int ch; 18 19 while (-1 ! = (ch = fi.read())) { 20 fo.write(ch); 21} 22} catch (FileNotFoundException e) {23 system.out.println (" file not found!" ); 24 System.exit(-1); 25} catch (IOException e) {26 system.out.println (" file read/write error! ); 27 System.exit(-1); 28 } finally { 29 try { 30 if (null ! = fi) { 31 fi.close(); 32 fi = null; 33 } 34 if (null ! = fo) { 35 fo.close(); 36 fo = null; 37 } 38 } catch (Exception e) { 39 e.printStackTrace(); 40 System.exit(-1); 41} 42} 43 44 system.out. println(" File copied successfully!" ); 46 45}}Copy the code


1 /* 2 This program proves that FileReader and FileWriter can only copy text files, 3 cannot copy audio files. 7 8 public class TestFileReaderWriterCopy { 9 public static void main(String[] args) { 10 FileReader fi = null; 11 FileWriter fo = null; 12 13 try {14 fi = new FileReader("E:\\ \\ \\ \\ \\ mp3"); 15 fo = new FileWriter("d:/share/Output.txt"); // output. TXT failed to open with player! 16 // This program proves that FileWriter and 17 // FileReader 18 // cannot complete the copy of audio files, FileWriter 19 // and FileReader 20 // can only copy text files 21 int ch; 22 23 while (-1 ! = (ch = fi.read())) { 24 fo.write(ch); 25} 26} catch (FileNotFoundException e) {27 system.out.println (" file not found!" ); 28 System.exit(-1); 29} catch (IOException e) {30 system.out.println (" file read/write error! ); 31 System.exit(-1); 32 } finally { 33 try { 34 if (null ! = fi) { 35 fi.close(); 36 fi = null; 37 } 38 if (null ! = fo) { 39 fo.close(); 40 fo = null; 41 } 42 } catch (Exception e) { 43 e.printStackTrace(); 44 System.exit(-1); 45} 46} 47 48 system.out.println (" file copied successfully!") ); 49}} 50Copy the code

 

Buffer flow

A buffered stream is an input/output stream with a buffer

Buffering streams can significantly reduce the number of IO accesses and protect our hard drives

Buffering is a process flow (wrap flow) that must be attached to the node flow (original flow).

A flow that processes a flow wrapped around the original node flow is equivalent to a pipe wrapped around a pipe

 

Buffered flows are “nested” on corresponding node flows, providing buffering function for read and write data, improving read and write efficiency, and adding some new methods. JAVA provides four types of buffered streams, which are commonly constructed as follows:

 

BufferedOutputStream and BufferedInputStream

BufferedOutputStream: BufferedOutputStream that allows more than one byte of data to be written to disk at a time.

BufferedInputStream: BufferedInputStream that allows more than one byte of data to be read into a program at a time.

BufferedOutputStream and BufferedInputStream are wrapped streams that must be attached to OutputStream and InputStream

Example: Copying large files using BufferedOutputStream and BufferedInputStream is much faster than using FileInputStream and FileOutputStream alone


1 /* 2 Copy large files using BufferedOutputStream and BufferedInputStream 3 This is much faster than using FileInputStream and FileOutputStream alone 4 5 BufferedOutputStream and BufferedInputStream are wrapped streams that must be attached to 6 InputStream and OutputStream 7 */ 8 9 import java.io.*; 10 11 public class TestBufferedInputStreamOutputStreamCopy { 12 public static void main(String[] args) { 13 BufferedOutputStream bos = null; 14 BufferedInputStream bis = null; 15 16 try { 17 bos = new BufferedOutputStream(new FileOutputStream("e:/OutputView.txt")); // bos 18 // Output streams have a default buffer, 20 bis = new BufferedInputStream(new FileInputStream("c:\\ www.66ys.cn] Finding Daddydvd 中 English subtitle.rmvb ")); // bis 21 // The input stream has a default buffer of 32 bytes 22 byte[] buf = new byte[1024]; 23 int len = bis.read(buf, 0, 1024); // It is important to note that the data is not read from buF, but from the file D:\\ variety \\ Movie \\ Cat and Mouse \\ CD4.rmVB to which BIS is associated. The read data is written to the bis' own default buffer, and the contents of the buffer are then written to the BUF array. Write (1024 bytes) to buF array at most, return the number of bytes actually written to buF array. If the end of the file is read and no more data can be written to BUF array, return -1 24 while (-1! = len) { 25 bos.write(buf, 0, len); 26 len = bis.read(buf); 26 len = bis.read(buf); // bis.read(buf); Equivalent to bis.read(buf, 0, 27 // buf.length); 28 } 29 bos.flush(); 30 bis.close(); 31 bos.close(); 32} catch (FileNotFoundException e) {33 system.out.println (" No file found!" ); 34 System.exit(-1); 35} catch (IOException e) {36 system.out.println (" file read/write error!" ); 37 System.exit(-1); 38} 39 40 system.out. println(" file copied successfully!") ); 41}} 42Copy the code


1 / * 2 slower in this procedure, speaking, reading and writing "TestBufferedInputStreamOutputStreamCopy. Java program 3" : 4 Copy large files using BufferedOutputStream and BufferedInputStream 5 This is much faster than using FileInputStream and FileOutputStream 6 7 BufferedOutputStream and BufferedInputStream are wrapped streams that must be attached to 8 OutputStream and OutputStream 9 */ 10 11 import java.io.*; 12 13 public class TestBufferedInputStreamOutputStreamCopy_2 { 14 public static void main(String[] args) { 15 FileOutputStream bos = null; 16 FileInputStream bis = null; 17 18 try { 19 bos = new FileOutputStream("e:/OutputView.txt"); 20 bis = new FileInputStream("c:\\[hd online www.66ys.cn] Finding Daddy.rmvb "); 21 22 byte[] buf = new byte[1024]; 23 int len = bis.read(buf, 0, 1024); 24 while (-1 ! = len) { 25 bos.write(buf, 0, len); 26 len = bis.read(buf); 27 } 28 bos.flush(); 29 bis.close(); 30 bos.close(); 31} catch (FileNotFoundException e) {32 system.out.println (" No file found!" ); 33 System.exit(-1); 34} catch (IOException e) {35 system.out.println (" file read/write error! ); 36 System.exit(-1); 37} 38 39 system.out. println(" File copied successfully!" ); 40}} 41Copy the code

Note that bis.read(buf,0,1024); Instead of reading data from BUF, it reads data from the “D:\\ variety \\ movie \\ Cat and Mouse \\ CD4.rmVB” file that BIS is associated with, writes the read data to the BIS ‘own default buffer, and then writes the contents of the buffer to the BUF array. Write a maximum of 1024 bytes to the BUF array at a time. Returns the number of bytes actually written to the BUF array. If no more data can be written to the BUF array after reading the end of the file, -1 is returned

The BufferedInputStream stream has a public int read(byte[] b) method that stores data read from the device to which the current stream is associated into a byte array

BufferedOutputStream has a public int Write (byte[] b) method that outputs data from the byte array to the device to which the current stream is associated

If we want to “import data from one device into another” with BufferedInputStream and BufferedOutputStream, we should define a temporary array of byte data and use this temporary array as a hub for input and output streams to interact.

 

BufferedReader and BufferedWriter

 

Example: Use BufferedReader and BufferedWriter to copy text files


1 /* 2 Copy text files using BufferedReader and BufferedWriter 3 */ 4 import java.io. 5 6 public class TestBufferedReaderWriterCopy { 7 public static void main(String[] args) { 8 BufferedReader br = null; 9 BufferedWriter bw = null; 10 11 try { 12 br = new BufferedReader( 13 new FileReader("C:\\Documents and Settings \ \ others \ \ desktop \ \ Java \ \ TestBufferedReaderWriterCopy Java ")); 14 bw = new BufferedWriter(new FileWriter("d:/share/Writer.txt")); 15 String str = null; 16 17 while (null ! = (STR = br.readline ())) // br.readline () reads a line of characters, but the newline is discarded automatically, i.e. the returned String does not include the newline 18 {19 bw. Write (STR); 20 bw.newLine(); // write a newline character that does not save 21} 22 bw.flush(); 23 } catch (FileNotFoundException e) { 24 e.printStackTrace(); 25 System.exit(-1); 26 } catch (IOException e) { 27 e.printStackTrace(); 28 System.exit(-1); 29 } finally { 30 try { 31 bw.close(); 32 br.close(); 33 } catch (IOException e) { 34 e.printStackTrace(); 35 System.exit(-1); 36} 37} 38} 39}Copy the code

 

DataInputStream DataOutputStream

DataInputStream can read JAVA primitive and String data directly from the underlying byte input stream in a machine-independent manner. Common methods include:

DataInputStream is a wrap stream and must be attached to InputStream

DataOutputStream provides the ability to write JAVA primitive and String data directly to other byte output streams in a machine-independent manner. Common methods include:

DataOutputStream is the package stream that must be attached to the OutputStream

Data flow examples:

Write data of type long to byte array, and then read the data from byte array.

* This is often done in Socket programming.

* This is because network programming often involves storing data in byte arrays, packaging byte arrays into datagrampackets, and transmitting the packets across the network to the destination machine, which then restores the original numeric data from the byte arrays.

}

This program uses:

DataInputStream 

DataOutputStream

ByteArrayInputStream

ByteArrayOutputStream


1 /* 2 functions: Write a long into the byte array, and then read out of the byte array 3 long 4 and 5 because network programming often has to store numeric data in the byte array and pack it into 6 DatagramPacket and send it over the network to the destination machine, 9 Destination: ByteArrayOutputStream DataOutputStream ByteInputStream DataInputStream 10 Remember: DataOutputStream writeLong(long n) is the binary code of n variable in memory 11 written to the device connected to the stream 12 13 note: ByteArrayInputStream {ByteArrayInputStream} ByteArrayInputStream {ByteArrayInputStream {ByteArrayInputStream}} 16 */ 17 18 import java.io.*; 19 20 public class TestByteArrayOutputStream1 21 { 22 public static void main(String args[]) throws Exception 23 { 24 long n = 9876543210L; 25 ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Line 9 API:" Public ByteArrayOutputStream(): Creates a new byte array output stream. The size of the buffer is initially 32 bytes and can be increased if necessary. "26 //9 lines of code, once executed, mean two things: 2. A pipe called BAOS is linked to this byte array. 27 // While it is possible to write data through baOS to the memory-allocated byte array to which baOS is attached, But ByteArrayOutputStream does not provide a way to write long data directly into the byte array to which the ByteArrayOutputStream is connected. Write (long, long, long, long, long, long, long, long, long); There is no such thing as writeLong() in ByteArrayOutputStream, DataOutputStream DOS = new DataOutputStream(baos); DataOutputStream DOS = new DataOutputStream(baos); 29 30 dos.writeLong(n); // Write the 10000L binary code in memory represented by the n variable into the 32 byte array of memory connected by the BAOS pipe attached to DOS. 31 32 dos.flush(); 31 32 dos.flush(); 31 32 dos.flush(); 33 byte[] buf = baos.toByteArray(); DataOutputStream does not have a toByteArray() method, but ByteArrayOutputStream does have a toByteArray() method. The meaning of the toByteArray() method in a ByteArrayOutputStream is taken from API "Create a newly allocated byte array." The size is the current size of this output stream, And the valid contents of the buffer are copied into the array. "34 35 // ByteArrayInputStream and DataInputStream can be used to get the value 10000L 36 from the byte array ByteArrayInputStream bais = new ByteArrayInputStream(buf); 37 DataInputStream dis = new DataInputStream(bais); 38 long l = dis.readLong(); 39 40 System.out.println("l = " + l); 41 dos.close(); 42}} to 43 and 44 / * 45 run results in JDK 1.6 is: 46 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - 47 l = 9876543210 48 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 49 * /Copy the code


1 /* 2 function: 3 Write data of type long to byte array, and then read data from byte array 4 */ 5 6 import java.io.*; 7 8 public class TestByteArrayOutputStream2 9 { 10 public static void main(String[] args) throws Exception 11 { 12 long n = 1234567; 13 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 14 DataOutputStream dos = new DataOutputStream(baos); 15 dos.writeLong(n); 16 17 byte[] buf = baos.toByteArray(); 18 ByteArrayInputStream bis = new ByteArrayInputStream(buf); 19 DataInputStream dis = new DataInputStream(bis); 20 long n2 = dis.readLong(); 21 System.out.println("n2 = " + n2); 22 23 dos.close(); 24 dis.close(); 26 25}}Copy the code

 

Conversion stream: OutputStreamWriter InputStreamReader

An OutputStreamWriter stream is a stream that converts an OutputStream to a Writer stream

An InputStreamReader stream converts an InputStream into a Reader

OutputStreamWriter and InputStreamReader are wrapped streams

Example: how to assign a String of keyboard input characters directly to a String.


1 /* 2 how to assign the keyboard input character String directly to the String object 3 5 -------------------------------- 6 Reader FileReader InputStream FileInputStream BufferedInputStream 7 There is no readLine in the stream Method 8 DataInputStream has the readLine method, but has been marked as obsolete 9 BufferedReader stream has the readLine method, And this method can be used right 10 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - 11 12 13 the import * / Java. IO. *; 14 15 public class TestStringInput 16 { 17 public static void main(String[] args) 18 { 19 String str = null; 20 BufferedReader br = new BufferedReader (//21 line 21 new InputStreamReader(system.in) 22); 23 24 try 25 {26 STR = br.readline (); 27} 28 Catch (IOException e) 29 {30 e.printStackTrace(); 31 System.exit(-1); 32 } 33 34 System.out.println("str = " + str); 35 try 36 { 37 br.close(); 38} 39 catch (IOException e) 40 {41 e.printStackTrace(); 42 System.exit(-1); 45}} 43 and 44} 46 / * 47 run results in JDK 1.6 is: 48 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 49 sadd administrative villages, 123 asd? Asd Satan 50 STR = SADD Administrative village 123Asd? Asd Satan 51 -------------------------------- 52 */Copy the code

 

ReadLine () and carriage return problems:

 

Print flow PrintWriter PrintStream

The Print stream has only output and no input

Classification:

PrintWriter Input character

PrintStream Output character

 

PrintWriter provides enhanced functionality over OutputStream to easily output formatted representations of various types of data, not just byte types.

PrintStream overloads the print and println methods for formatting output of various types of data.

To format output means to output a piece of data in its string format.

 

The WriteXXX(data) method in DataOutputStream writes binary data in memory to a file

Println (data) in PrintStream is the formatted string of data written to the file


1 /* 2 DataOutputStream writeXXX(data) method 3 and 4 PrintStream println(data) method 5 6 7 The writeXXX(data) method in DataOutputStream is to write binary data in memory to a file. 8 Println (data) in PrintStream is to write the formatted string of the data 9 */ 10 11 import java.io.*; 12 13 public class TestPrintStream_1 14 { 15 public static void main(String[] args) throws Exception 16 { 17 DataOutputStream dos = new DataOutputStream(new FileOutputStream("d:/share/kk.txt")); 18 dos.writeLong(12345); 00 00 00 00 00 30 39 19 dos.close(); 20 System.out.printf("%#X\n", 12345); 21 22 PrintStream ps = new PrintStream(new FileOutputStream("d:/share/kk2.txt"), true); 23 ps.println(12345); // '1' 2' 3' 4' 5' 24 ps. Close (); 26 25}}Copy the code

 

PrintWriter provides all of PrintStream’s printing methods, and its methods never throw ioExceptions.

Difference with PrintStream:

 

Standard I/O redirection:

Example: programming implementation of the keyboard input data into A file, if the input is wrong, the error message output to B file


1 import java.io.*; 2 3 public class TestSetSystemOut { 4 public static void main(String[] args) { 5 PrintStream ps_out = null; 6 7 try { 8 ps_out = new PrintStream(new FileOutputStream("d:/share/ww.txt")); 9 System.setOut(ps_out); // Change the value of system. out to ps_out, that is, system. out is not associated with the display, but with "d:/share/ww. TXT "file 10 system.out.println (12); 11 system.out.println (55.5); } catch (Exception e) {13 e.printstackTrace (); 14 } finally { 15 try { 16 ps_out.close(); 17 } catch (Exception e) { 18 e.printStackTrace(); 19} 20 21} 22} 23}Copy the code


1 /* 2 Function: input the keyboard data into file A, if the input is wrong, 3 output the error information to file B 4 5 Redirection of standard INPUT and output streams 6 */ 7 8 import java.io.*; 9 import java.util.*; 10 11 public class TestSetOutErr { 12 public static void main(String[] args) { 13 PrintStream psOut = null; 14 PrintStream psError = null; 15 Scanner sc = null; 16 17 try { 18 psOut = new PrintStream("d:/Out.txt"); 19 psError = new PrintStream("d:/error.txt"); 20 sc = new Scanner(System.in); 21 int num; 22 System.setOut(psOut); 23 System.setErr(psError); 24 25 while (true) { 26 num = sc.nextInt(); 27 System.out.println(num); 28} 29} catch (Exception e) {30 system.err.println (" error message :"); // System.out.println(" error message :"); 31 e.printStackTrace(); // e.printStackTrace(); The default is to output to the device associated with system. err 32} 33} 34}Copy the code

 

ObjectOutputStream ObjectInputStream

Example:


1 import java.io.*; 2 3 public class TestObjectIO 4 { 5 public static void main(String[] args) 6 { 7 ObjectOutputStream oos = null; 8 ObjectInputStream ois = null; 9 Student ss = new Student("zhansan", 1000, 888f); Student ss2 = null; 11 12 try 13 { 14 FileOutputStream fos = new FileOutputStream("d:/share/java/ObjectOut.txt"); 15 oos = new ObjectOutputStream(fos); 16 oos.writeObject(ss); 17 18 ois = new ObjectInputStream(new FileInputStream("d:/share/java/ObjectOut.txt")); 19 ss2 = (Student)ois.readObject(); //(Student) can't save ois.readObject(); If a member in ois is transient, it will not be read because it will not be saved. ! 20 21 System.out.println("ss2.sname = " + ss2.sname); 22 System.out.println("ss2.sid = " + ss2.sid); 23 System.out.println("ss2.sscore = " + ss2.sscore); 24} 26 catch (FileNotFoundException e) 26 {27 system.out.println (" file not found!" ); 28 System.exit(-1); 29 } 30 catch (Exception e) 31 { 32 e.printStackTrace(); 33 System.exit(-1); 34 } 35 finally 36 { 37 try 38 { 39 oos.close(); 40 ois.close(); 41 } 42 catch (Exception e) 43 { 44 e.printStackTrace(); 45 System.exit(-1); 51 class Student implements Serializable // Implements Serializable 52 {53 public String sname = null; 54 public int sid = 0; 55 transient public float sscore = 0; // Indicates that the sscore member cannot be serialized. "This member is not saved when it calls writeOnbject() of ObjectOutputStream, 56 57 Public Student(String name, int id, ObjectInputStream) float score) 58 { 59 this.sname = name; 60 this.sid = id; 61 this.sscore = score; 63 62}}Copy the code

Analysis of ArrayList source serialization and deserialization problems
Calls to subclass and superclass constructors in serialization