Java IO input/output stream notes

Source: Internet
Author: User
Tags create directory int size object serialization

String s = "mu lesson abc"; byte[] bytes1 = S.getbytes ();//convert to byte sequence using the project default encoding, encoding Gbkfor (byte b:bytes1) {//bytes (converted to) int is displayed in 16 binary mode, only Show post 8-bit System.out.println (integer.tohexstring (b & 0xff) + ""); GBK encoding Chinese occupies two bytes, English occupies 1 bytes//utf-8 encoding Chinese occupies 3 bytes, English occupies 1 bytes byte[] bytes2 = s.getbytes ("Utf-8"); for (byte b:bytes2) { System.out.print (integer.tohexstring (b & 0xff) + "");


Java is a double-byte encoding, UTF-16BE encoding, it occupies two bytes in Chinese, English is two bytes

When your byte sequence is some kind of encoding, this time you want to turn the byte sequence into a string, you also need to use this encoding method, otherwise it will appear garbled.

String str2 = new String (bytes4, "utf-16be");

A text file is a sequence of bytes, which can be any encoded sequence of bytes. If we create a text file directly on a Chinese machine (which can be recognized if copied in the past), the text file only knows the ANSI encoding.


File Class

The Java.io.File class is used to represent files (directories)

The file class is used only to represent information (name, size) of files (directories), etc., and cannot be used for access to file content

File File = new file ("D:\\javaio");//system.out.println (File.exists ());//Whether the document exists if (!file.exists ())//whether there is File.mkdir ( );//Create directory//file.mkdirs multilevel directory elsefile.delete (); System.out.println (File.isdirectory ());//Is the directory, is the directory return TrueSystem.out.println (File.isfile ());//is the file//file file2 = New File ("D:\\javaio\\ diary 1.txt"); File File2 = new file ("D:\\javaio", "Journal 1.txt"), if (!file2.exists ()) try{file2.createnewfile ();//Create Files}catch ( IOException e) {e.printstacktrace ();} Elsefile2.delete ()///File Delete//APISYSTEM.OUT.PRINTLN of the commonly used file object, contents of//file.tostrint (), Directory System.out.println ( File.getabsolutepath ()); System.out.println (File.getname ());//The name of the file or directory System.out.println (File.getparent ());//The path of the parent directory// Lists all files under the specified directory (including its subdirectories) public static void ListDirectory (file dir) throws Ioexception{if (!dir.exists ())//does not exist {throw new IllegalArgumentException ("directory" +dir+ "does not Exist");} if (!dir.isdirectory ())//is not a directory {throw new IllegalArgumentException (dir+ "is not a Directory");} string[] filenames = dir.list (); The list () method is used to list subdirectories and file names under the current directory, an array of strings that contains the names of subdirectories, and does not contain the contents of subdirectories for(String string:filenames) {System.out.println (string);} If you want to traverse the contents of the sub-directory, you need to construct a file object to do the recursive operation, file provides a direct return to the file object apifile[] files = dir.listfiles ();//Returns the abstract of the direct subdirectory (file), does not do the recursive if ( Files = null && files.length > 0) {for (file file:files) {if (File.isdirectory ()) {listdirectory (file);//Recursive operation} elsesystem.//Output}}}

Randomaccessfile

Java provides access to the contents of the file, can read files, or write files, support random access to files, can access any location of the file.

(1) Java file Model: A file on the hard disk is stored in byte byte byte and is a collection of data

(2) Open file has two modes "RW" read-write "R" read-only

Randomaccessfile RAF = new Randomaccessfile (file, "RW");

File pointer, pointer = 0 when opening a file;

(3) Writing files

Raf.write (int) writes only one byte (only the last 8 bits of int), and the pointer points to the next position, ready to write again

(4) Method of Reading

int b = Raf.read () read one byte

(5) The file must be closed after reading and writing (there may be unexpected errors)


File read and write process:

File Demo = new file ("D:\\demo"), if (!demo.exists ()) Demo.mkdir (); File File = new file (demo, "Raf.dat"), if (!file.exists ()) file.createnewfile (); Randomaccessfile RAF = new Randomaccessfile (file, "RW"); System.out.println (Raf.getfilepointer ());//Get pointer position, the value is 0raf.write (' a '),//write a after 8 bits written in, write only one byte System.out.println ( Raf.getfilepointer ());//Get the pointer position, at this time the value bit 1int i = 0x7fffffff;//Write one byte at a time, if you want to write I go to write 4 times raf.write (I >>> 24) ;//High 8-bit raf.write (i >>>); Raf.write (I >>> 8); Raf.write (i); System.out.println (Raf.getfilepointer ());//Obtain the pointer position, at this time for 5//can write a intraf.writeint directly (i); String s = "medium"; byte[] GBK = s.getbytes ("GBK"); Raf.write (GBK); System.out.println (Raf.length ());//Read the file, you must move the pointer to the head raf.seek (0);//Read the contents of the file into a byte array, one-time read byte[] buf = new byte[(int) Raf.length ()];raf.read (BUF); System.out.println (arrays.tostring (BUF));//output [65, 127,-1,-1,-1, 127,-1,-1,-1,-42,-48] 65 is ' A ' string s1 = new string (BUF, "GBK"); System.out.println (S1); for (byte b:buf) {System.out.println (integer.tohexstring (b & 0xFF) + "");} Raf.close ();//Close file

IO stream (input stream, output stream)

Byte stream, character stream

1. Byte stream

(1) inputstream outputstream abstract class

InputStream abstracts the way the application reads data

OutputStream abstracts the way the application writes data

(2) EOF = end Read-1 reading to the end

(3) Input stream keyboard input is input stream

Basic methods:

int b = In.read ();//read one byte unsigned padding to the lower 8 bits of int, other bit complement 0

In.read (byte[] buf) reads data into a byte array buf

In.read (byte[] buf,int start, int size) reads the data into a byte array buf, starting from the start position and placing up to how many

(4) Output stream

Out.write (int b) writes out a byte-to-stream and writes the lower 8 bits of B

Out.write (byte[] buf) writes the byte array buf to the stream

Out.write (byte[], int start, int size)


(5) Subclass FileInputStream ---specifically implements reading data on a file

/read file contents, output to console according to 16, and 10 byte newline per output, one byte read public static void Printhex (String fileName) throws ioexception{ FileInputStream in = new FileInputStream (fileName);//Read the file as a byte stream int b;int i = 1;while ((b = In.read ())! =-1)//read to a bytes {Sys Tem.out.print (integer.tohexstring (b) + ""); if (i + +% = = 0) {System.out.println ();}} In.close ();} Bulk read bytes public static void Printhexbybytearray (String fileName) throws ioexception{fileinputstream in = new FileInputStream (fileName);//Read the file as a byte stream byte[] buf = new byte[8*1024];//Bulk read bytes from in, put buf in this byte array, starting at 0 positions, Up to Buf.length//return is the number of bytes read/*int bytes = in.read (buf, 0, buf.length);//Once read, the byte array is large enough int j = 1;for (int i = 0; i < byt Es i + +) {if (Buf[i] <= 0xf) System.out.print ("0"); System.out.print (Integer.tohexstring (buf[i]) + ""); if (j + +% = = 0) {System.out.println ();}}  *///array is not large enough to do, workaround int bytes = 0;int j = 1;while ((bytes = In.read (buf, 0, buf.length))! =-1) {for (int i = 0; i < bytes; I + +) {System.out.print (integer.tohexstring (Buf[i] & 0xff) + "");if (j + +% = = 0) System.out.println ();}} In.close ();}

Single-byte reads are not suitable for large files, and large files are inefficient

Bulk byte reading, high efficiency for large files, is also the most common way to read files


(6) FileOutputStream implements the method of writing byte data to a file

If the file does not exist, it is created directly, if present, after deletion creates fileoutputstream out = new FileOutputStream ("Demo/out.dat");  If you want to append, the argument is "Demo/out.data", true  true to indicate whether to append Out.write (' a '),//write the low 8-bit out.write (' B ') of ' a ',//write the ' B ' low 8-bit int a = 10;/ /write can only write 8 bits, write int need to write four times out.write (a >>>), Out.write (a >>>16); Out.write (a >>> 8); out.write (a); byte[] GBK = "China". GetBytes ("GBK"); Out.write (GBK); Out.close ();

/Copy one file to another file the fastest public    static void CopyFile (file srcfile, file destfile) throws Ioexception{if (!srcfile.exists () {throw new IllegalArgumentException ("File:" + srcfile + "does not exist");} if (!srcfile.isfile ()) {throw new IllegalArgumentException ("File:" + srcfile + "not file");} FileInputStream in = new FileInputStream (srcfile); FileOutputStream out = new FileOutputStream (destfile); byte[] buf = new byte[8 * 1024];int b;while ((b = in.read (buf, 0, buf . length))! =-1) {out.write (buf, 0, B); Out.flush ();//Clear Output stream}in.close (); Out.close ();}

(7) DataOutputStream DataInputStream

Extension of "stream" function, can read int long character and other type data more.

Dataoutstream writeint ()/Writedouble/writeutf ()

<span style= "White-space:pre" ></span>string file = "Demo/dos.dat";D ataoutputstream dos = new DataOutputStream (file);d os.writeint (FileOutputStream);d os.writeint ( -10);d Os.writelong (100); Dos.writedouble (10.5);//write Dos.writeutf ("China") with utf-8 code;//Write Dos.writechars ("China") in Utf-16be code;d os.close ();D Atainputstream dis = new DataInputStream (new FileInputStream (file)); int i = Dis.readint ();


(8) bufferedinputstream bufferedoutputstream

These two stream classes provide the IO with buffer operations, usually open the file for write or read operations, will be buffered,

This flow pattern improves the performance of the IO.

Putting data into a file from an application is equivalent to pouring a jar of water into another cylinder

FileOutputStream-->write () is equivalent to a drop of water to "transfer" the past

The DataOutputStream-->writexxx () method will be convenient, equivalent to a scoop of a scoop of the transfer of the past

Bufferedoutputstream--->writexxx () method is more convenient, equivalent to a scoop of water first into the bucket, and then poured from the barrel into another cylinder, performance improvement

public static void Copyfilebybuffer (file srcfile, file destfile) throws ioexception{// Copy the file using buffered byte stream Bufferedinputstream bis = new Bufferedinputstream (   new FileInputStream (srcfile)); Bufferedoutputstream BOS = new Bufferedoutputstream (   new FileOutputStream (destfile)); int C;while ((c = Bis.read ())! =-1) {bos.write (c); Bos.flush ();//flush buffer, must write}bis.close (); Bos.close ();}

2. character Stream

1) Coding issues

2) Recognize text and text files

Java text (char) is a 16-bit unsigned integer, which is the Unicode encoding of the character (double-byte encoding)

File is a byte of byte byte .... The data series

A text file is a stored result of a sequence of text (char) serialized into Byte according to an encoding scheme (Utf-8 UTF-16BE,GBK)

3) the character stream (Reader Writer) operates on a text file

Processing of characters, one character at a time

The bottom of the character is still the basic byte sequence.

Basic implementation of character stream

InputStreamReader completes a byte stream parsing to a char stream, parsed by encoding

Outputstreamreader provides a char stream to a byte stream, which is processed by encoding

FileInputStream in = new FileInputStream ("D:\\sr.txt"); InputStreamReader ISR = new InputStreamReader (in);//Default item encoding, The encoding of the file to be written fileoutputstream out = new FileOutputStream ("D:\\sx.txt"); OutputStreamWriter OSW = new OutputStreamWriter ( out);/*int c;while ((c = Isr.read ())! =-1) {System.out.print ((char) c);} */char[] buffer = new CHAR[8 * 1024];int c;//Bulk Read, put in buffer this character array, starting from No. 0, put up buffer.length//Return is the number of characters read while (c = Isr.read (buffer, 0,buffer.length))! =-1) {string s = new String (buffer, 0, c); osw.write (buffer, 0, C); System.out.print (s);} Osw.close (); Isr.close ();


Filereader/filewriter


FileReader FR = new FileReader ("D:\\sr.txt"); FileWriter FW = new FileWriter ("D:\\sx.txt");//You can add a parameter, true whether to append char[] buffer = new Char[2056];int C;while ((c = Fr.read (b Uffer, 0, buffer.length))! =-1) {fw.write (buffer, 0, c); Fw.flush ();} Fr.close (); Fw.close ();


Convenient, but does not correctly read the file is not the default encoding, otherwise garbled, filereader fr = new FileReader ("D:\\sr.txt"); no second parameter (encoding)


Filter for character streams

BufferedReader --read one line at a time

bufferedwriter/printwriter ---> Write a line

Read and write to the file BufferedReader br = new BufferedReader (new InputStreamReader (New FileInputStream ("D:\\sr.txt"));/* BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (New FileOutputStream ("D:\\sx.txt")); */printwriter pw = New PrintWriter ("D:\\sx.txt"); String Line;while (line = Br.readline ())! = null) {System.out.println (line);//read one row at a time and does not recognize newline//bw.write (lines);// Write the newline action separately//bw.newline ();//bw.flush ();p w.println (line);p W.flush (); Br.close ();//bw.close ();p w.close ();

3. serialization of objects, deserialization

1) object serialization, that is, the object is converted to a byte sequence, the inverse is called the deserialization of objects

2) serialized Stream (Objectoutstream), which is the filter flow---writeobject method

Deserialization Stream (ObjectInputStream),---readobject method

3) serialization Interface (Serializable)

Object must implement a serialization interface for serialization, or an exception will occur

This interface, without any method, is just a standard

public class Student implements Serializable {private string stuno;private string stuname;private int stuage;public Studen T () {}public Student (string Stuno, string stuname, int stuage) {super (); This.stuno = Stuno;this.stuname = Stuname;this.stu age = Stuage;} Public String Getstuno () {return stuno;} public void Setstuno (String stuno) {This.stuno = Stuno;} Public String Getstuname () {return stuname;} public void Setstuname (String stuname) {this.stuname = Stuname;} public int getstuage () {return stuage;} public void setstuage (int stuage) {this.stuage = Stuage;} @Overridepublic String toString () {return "Student [stuage=" + Stuage + ", stuname=" + stuname+ ", stuno=" + Stuno + "]";} }public static void Main (string[] args) throws IOException, classnotfoundexception{string file = "D:\\1.dat",//1. Serialization of Objects/ *objectoutputstream Oos = new ObjectOutputStream (newfileoutputstream (file)); Student stu = new Student ("1002", "SR", N); Oos.writeobject (Stu); Oos.flush (); Oos.close (); */// Deserialization of the object ObjectInputStream OIS = nEW ObjectInputStream (new FileInputStream (file)); Student stu = (Student) ois.readobject (); System.out.println (Stu); Ois.close ();}


private transient int stuage;//This element does not perform JVM default serialization, in some cases some variables do not need to be transferred over the network

Does not mean that it cannot be serialized or that it can be serialized by itself

4)

Import Java.io.serializable;import Java.util.jar.jarexception;public class Student implements Serializable {private String Stuno;private string stuname;private transient int stuage;//The element does not make the JVM default serialization public Student () {}public Student ( String Stuno, String stuname, int stuage) {super (); This.stuno = Stuno;this.stuname = Stuname;this.stuage = Stuage;} Public String Getstuno () {return stuno;} public void Setstuno (String stuno) {This.stuno = Stuno;} Public String Getstuname () {return stuname;} public void Setstuname (String stuname) {this.stuname = Stuname;} public int getstuage () {return stuage;} public void setstuage (int stuage) {this.stuage = Stuage;} @Overridepublic String toString () {return "Student [stuage=" + Stuage + ", stuname=" + stuname+ ", stuno=" + Stuno + "]";} private void WriteObject (Java.io.ObjectOutputStream s) throws Java.io.ioexception{s.defaultwriteobject ();//  Serializes the elements that the JVM can default to serialize S.write (stuage);//self-completed stuage serialization}private void ReadObject (Java.io.ObjectInputStream s) throws Java.io.IOEXception, Classnotfoundexception{s.defaultreadobject ();//reverse-sequence The elements that the JVM can default to serialize This.stuage = S.readint ();// Complete the deserialization of Stuage}}


5) serialization of a call to a child class and a parent class constructor
A class implements a serialized interface, and its subclasses can be serialized.


When a sub-class object is deserialized, the constructor of its parent class is called if its parent does not implement the serialization interface.

Java IO input/output stream notes

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.