1. file output stream (java IO Introduction)
/** * Input and output standard java io * Use java IO device to the outside world that we can have in the same way * Read the data exchange is completed. * * Java IO to "read" and "write" were divided according to directions: Operating from the outside to the direction of the program for the program to get outside so the input data is "read" the data: * Input * Output: from the outside in the direction of the program, the data for the "write" the operation. * * Java IO read and write functions represented in the form of "flow" * Java.io.InputStream input stream, the input stream we can * Connected to the external apparatus to thereby read the device data * Java.io.OutputStream output stream * Two or more streams of all input stream and an output stream of bytes superclass, provides * All input streams and output streams of the basic read and write functions. * * Java stream into two categories: nodes with the process flow stream * * Node Stream: also known as "low-flow", is a real connection to the data source program * "Pipe" for transporting the actual data stream. Read it must be based on * Conducted on the basis of the flow nodes. * * Process Flow: also known as "High flow", Advanced Streaming can not exist independently, must * Connected to the other stream, when its purpose is to make the current flowing through the data stream * Some processing, to simplify the operation of our respective read and write data. * * Actual use IO, we usually final series of several high-level flow connection * To the lower stream, so that read and write data to the pipelined processing is completed, * This operation is called "connection flow", where also the essence of IO * File stream * A low-level file stream flow, is connected to the role of the file for reading and writing * File data. * Java.io.FileOutputStream: file output stream * Java.io.FileInputStream: file input stream */ public class FOSDemo { public static void main(String[] args) throws IOException { /* * Constructor file stream provided: * FileOutputStream(File file) * FileOutputStream(String path) * Create the above two ways, to cover the default write mode, namely: * If the specified file already exists, so will the original file * Delete all data. Then writes the new data file. * * FileOutputStream(File file,boolean append) * FileOutputStream(String path,boolean append) * Two or more configuration allows reinjecting a boolean type * Parameter, if true, the file output stream is an additional write mode * Namely: data in the original data are retained, new content will be appended to the end of the file * File stream with the RAF difference: * RAF is a pointer-based random access form, any file can be * Location read or write operation can be done on the data file section * Cover other operations. Read more flexible. * * File stream is based on the standard Java IO write, and sequential IO * Read-write mode, namely: only write or read data back, can not be rolled back. * * Single flexibility in terms of reading and writing from the RAF is better than the file stream, but * File stream flow connection can be done based on a complex java IO * Read and write data, it is not easy to do RAF. * / A FileOutputStream fos = new new a FileOutputStream ( "./ fos.txt", to true ); // String = Line "back, dig ~"; // fos.write (line.getBytes ( "UTF-. 8")); / / fos.write ( "ghost knife opened invisible ~ ~ walk walk ~" .getBytes ( "UTF-8" )); fos.write ( "hand" .getBytes ( "UTF-. 8" )); System.out.println ( "write is completed!" ); fos.close(); } }
2. file input stream
/** * File input stream for reading data from the file */ public class FISDemo { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("fos.txt"); byte[] data = new byte[1000]; int len = fis.read(data); String str = new String(data,0,len,"UTF-8"); System.out.println(str); fis.close(); } }
3. File Copy (byte blocks)
/** * Use file stream file copy is completed */ public class CopyDemo { public static void main(String[] args) throws IOException { /* * 1: Create a file input stream to read the original document * 2: Create a file output stream for writing copy files * 3: byte write cycle to read from the original file to copy the file * 4: Close two streams */ FileInputStream fis = new FileInputStream("movie.mp4"); Fos a FileOutputStream = new new a FileOutputStream ( "movie_cp.mp4" ); int len = -1; // the amount of bytes actually read record each byte [] = Data new new byte [1024 * 10 ]; the while ((len = FIS .read (Data)) = -!. 1 ) { fos.write(data,0,len); } System.out.println ( "copy is complete!" ); fos.close(); fis.close(); } }
4. The stream buffer
/** * Buffer flow * java.io.BufferedOutputStream * java.io.BufferedInputStream * * A pair of buffer level flow stream, the stream acting in the connection is to increase the efficiency of reading and writing * When we write operation is performed such that the single byte can be used to improve efficiency of reading and writing. * * The reason why the stream buffer can improve the efficiency of reading and writing, because there is an internal buffer flow * A buffer (a byte array), whether we use the stream buffer * Which read (one byte write or block) will eventually be converted to a stream buffer * Read block to improve the efficiency */ public class CopyDemo2 { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("music.mp3"); BufferedInputStream bis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream("music_cp2.mp3"); BufferedOutputStream bos = new BufferedOutputStream(fos); int d = -1; while((d = bis.read())!=-1) { bos.write(d); } System.out.println ( "copy is complete!" ); bis.close(); bos.close(); } }
The buffered output stream of the buffer
/** * Problem buffered output stream buffer */ public class BOS_flush { public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("bos.txt"); BufferedOutputStream bos = new BufferedOutputStream(fos); bos.write ( "Rubbing pace devil ~ ~" .getBytes ( "UTF-. 8" )); / * * void flush() * Flush method is a method defined in the OutputStream, * All output streams have this method, but only a buffer * Meaningful flow of the method. The method has other streams * The purpose of the buffer is passed to the buffering operation in the flow stream connection * * Flush role is to buffer the data stream of one-time cached write. * Frequent calls flush method will increase the number of written so * Reduce write efficiency, but can guarantee real-time data is written. * / // bos.flush (); System.out.println ( "write is completed!" ); bos.close(); } }
6. The output stream objects
/** * Object flow * java.io.ObjectOutputStream * java.io.ObjectInputStream * * A pair of advanced object flow stream, the stream acting in the connection is easy to read and write * Java object. (Object byte stream conversion is completed by the object) */ public class OOSDemo { public static void main(String[] args) throws IOException { /* * Person instance will write a file in person.obj */ String name = "苍老师"; int age = 18; String gender = "女"; String [] otherInfo = { "an actor", "hobby is calligraphy," "gave birth to twins," "promote the Sino-Japanese cultural exchange" }; Person p = new Person(name, age, gender, otherInfo); FileOutputStream fos = new FileOutputStream("person.obj"); ObjectOutputStream oos = new ObjectOutputStream(fos); /* * This method may throw: NotSerializableException * When a class written object belongs not implement Serializable * When will throw the exception. * * After writing the actual data file found in the file than the current object * Save the content to be large, because it contains a set of bytes in addition to * Outside the data structure information of the object as well as the object. */ oos.writeObject(p); System.out.println ( "write is completed!" ); oos.close(); } }
7. object input stream
/** * Object input stream */ public class OISDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { /* * The person.obj file object read out */ FileInputStream fis = new FileInputStream("person.obj"); ObjectInputStream ois = new ObjectInputStream(fis); Person p = (Person)ois.readObject(); System.out.println(p); ois.close(); } }
8. The flow character output conversion
/** * Character stream * java.io.Reader和java.io.Writer * The above two class is the superclass of all character stream, provides stream are all characters * Related methods must have read and write characters. * * Java stream into a byte stream in accordance with the read-write unit character stream Char * character stream in a unit of reading and writing data itself or the underlying read and write * Byte, except that the character byte character stream conversion to complete. * * Conversion flow * java.io.InputStreamReader * java.io.OutputStreamWriter * Convert a character stream flow, but they are also high-level flow, in the actual development * We usually do not directly operate the two streams, but the data in read and write text * When the flow connection they are a very important part. Cohesion responsible for other characters * Advanced stream and byte stream. */ public class OSWDemo { public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("osw.txt"); /* * When creating a stream conversion usually passed in the second argument, this * Parameter is used to specify the character set, so that the current flow through the write * After the text data are converted into bytes according to the character set * Write. */ OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8"); osw.write ( "and I walk the streets in Chengdu ~" ); osw.write ( "until all the lights went out not to stay." ); System.out.println ( "write is completed!" ); osw.close (); } }
9. The character input commutations
/** * Used to read text data stream conversion */ public class ISRDemo { public static void main(String[] args) throws IOException { // RandomAccessFile raf = new RandomAccessFile("osw.txt","r"); // byte[] data = new byte[(int)raf.length()]; // raf.read(data); // String str = new String(data,"UTF-8"); // System.out.println(str); // raf.close(); // FileInputStream fis = new FileInputStream("osw.txt"); // byte[] data = new byte[1000]; // int len = fis.read(data); // String str = new String(data,0,len,"UTF-8"); // System.out.println(str); // fis.close(); FileInputStream fis = new FileInputStream("osw.txt"); InputStreamReader isr = new InputStreamReader(fis,"UTF-8"); // char[] data = new char[100]; // int len = isr.read(data); // String str = new String(data,0,len); // System.out.println(str); int d = -1; while((d = isr.read())!=-1) {//可以一次读一个字符 System.out.print((char)d); } isr.close(); } }
10. The character input stream buffer
/** * Buffer character-input stream * java.io.BufferedReader * Block read text data, and can be read by a string line. */ public class BRDemo { public static void main(String[] args) throws IOException { /* * The source code for the current content to the console. */ FileInputStream fis = new FileInputStream("./src/io/BRDemo.java"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); /* * String readLine() * Continuous reading a number of characters read until a newline * So far, the characters before the newline character * The string is returned. If the returned value is null, a flow to the end of the reading. */ String line = null; while((line = br.readLine())!=null) { System.out.println(line); } br.close(); } }
11. The character output stream buffer
/** * Buffer character stream * java.io.BufferedWriter * java.io.BufferedReader * Write buffer block is text data stream, to improve efficiency of reading and writing. And * Can be written and read by the string. * * Java.io.PrintWriter with automatic line flushing buffer * Character output stream as internal always connected BufferedWriter * Its buffer accelerator operation. */ public class PWDemo1 { public static void main(String[] args) throws IOException { /* * Wrote the string pw.txt file * Internal configuration of the streaming method automatically connecting operation, * Character stream respectively connected to the buffer, and converts the stream file stream. */ PrintWriter pw = new PrintWriter("pw.txt","UTF-8"); pw.println ( . "I burst into tears, not just last night's wine" ); pw.println ( "Let me fond memories, not just your gentleness." ); System.out.println ( "write is completed!" ); pw.close(); } }
/** * Self-complete text stream connection using the write data PW */ public class PWDemo2 { public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("pw2.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8"); BufferedWriter bw = new BufferedWriter(osw); Pw PrintWriter = new PrintWriter (bw)? pw.println(""); System.out.println ( "write is completed!" ); pw.close(); } }
Flow Graph 12.IO
13.IO integrated application streaming
/** * Simple Notepad tool to achieve * After the program starts, asking for a file name, then write to the file contents. * Each row in the subsequent console input character string are written to the row * This file, when separate input exit, the program exits. * * Requirements: PW created using streaming connections themselves */ public class PWDemo3 { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); System.out.println("请输入文件名:"); String fileName = scanner.nextLine(); FileOutputStream fos = new FileOutputStream(fileName); OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8"); BufferedWriter bw = new BufferedWriter(osw); /* * 创建PrintWriter时使用的构造方法如 * 过第一个参数是一个流,那么就支持第 * 二个参数,这个参数是一个boolean值, * 该值为true时就打开了自动行刷新功能 * 此时每当调用println方法写出一行字符 * 串都会自动flush. */ PrintWriter pw = new PrintWriter(bw,true); System.out.println("请开始输入内容:"); while(true) { String line = scanner.nextLine(); if("exit".equals(line)) { break; } pw.println(line); } System.out.println("再见!"); pw.close(); } }