Java Learning lesson 47th-io Stream (a): Read and write files

Source: Internet
Author: User

Input stream and output stream relative to memory

To read data from an external device into memory: input

Writes in-memory data to an external device: output

Common base classes for IO streams

Abstract base class for byte stream: Inputstream,outputstream

Abstract base class for characters: Reader,writer

PS: Subclasses born of these four genres are named after the name of the parent class

For example: derived class of InputStream derived class Fileinputstream,reader FileReader

PS: If the data in text form should take precedence on character stream, and write data from memory to hard disk it should be writer

FileWriter class

Demo: Save text to your hard disk (FileWriter)

Import Java.io.filewriter;import Java.io.ioexception;public class Main {public static void main (string[] args) throws IOE xception{//If the file does not exist, it will automatically be created, existing, will overwrite FileWriter fw = new FileWriter ("Demo.txt");//Throw exception//Call write method in writer, write data, But the data is actually written to the temporary storage buffer fw.write ("hello");//Flushes the buffer of the stream with the Flush method. If the stream has saved all the characters of the various write () methods in the buffer, they are immediately written to the intended destination. Fw.flush ();//You can use multiple//close resources//Close the stream, close the resource, and call flush to refresh the data in the buffer before closing to the destination//API document: Close the stream, but refresh it first. After you close the stream, calling write () or flush () will cause the IOException to be thrown. Closing a previously closed stream is not valid. Fw.close ();//can only be used once}}

Details

Import Java.io.filewriter;import Java.io.ioexception;public class Main {private static final String Line_separator = Syst Em.getproperty ("Line.separator");p ublic static void Main (string[] args) throws Ioexception{filewriter fw = new FileWriter ("Demo.txt", true);//constructor, add a true to achieve the continuation of the file Fw.write ("Hello" +line_separator+ "World");//windows next line is \ r \ n, Linus is \nfw.write (line_separator+ "ads"); Fw.flush (); Fw.close ();}}

Basic handling of flow anomalies

Create a reference outside the try, create an object inside it, to determine if it is a null pointer when closing

Import Java.io.filewriter;import Java.io.ioexception;public class Main {private static final String Line_separator = Syst Em.getproperty ("Line.separator");p ublic static void Main (string[] args) {FileWriter FW = null;try {fw = new FileWriter ("Z: \\Demo.txt ", true);//If passing in an address that cannot be found throws two exceptions//cannot find the file exception, null pointer exception, so the finally part, plus a sentence to determine whether it is a null pointer fw.write (" Hello "+line_separator+" world "); Fw.flush ();} catch (Exception e) {System.out.println (e.tostring ());} finally{//finally try again, processing if (fw!=null) {try {fw.close ()},} catch (IOException e) {throw new RuntimeException ("Close Failed");}}}}

FileReader class

Reads a text file and prints the read data to the console

Import Java.io.filereader;import Java.io.ioexception;public class Main {public static void main (string[] args) throws IOE Xception {//Be sure to ensure that the file is present FileReader fr = new FileReader ("G:\\java\\main\\demo.txt");//file contents are Ab//read methods, characters read as integers, range from 0 to 65535 (0X00-0XFFFF), if the end of the stream is reached, 1//int c = fr.read (),//system.out.println ((char) c);//int C1 = Fr.read ();// System.out.println (char) c1);//int C2 = Fr.read ();//system.out.println (C2);//-1int temp;while ((temp = Fr.read ())!=-1 ) {System.out.println (temp);} Fr.close ();}}

The Read () method also has an overloaded form of reading an array: high efficiency

Import Java.io.filereader;import Java.io.ioexception;public class Main {public static void main (string[] args) throws IOE xception {FileReader fr = new FileReader ("G:\\java\\main\\demo.txt");//The file content is abcdef//using read (char[] a) to read the text file data/* * The character array is created first,  *///char ch[] = new Char[5];//int num = Fr.read (CH),//The characters are stored in the array, num is the number of characters//system.out.println (num+ ": "+new string (ch));//5:abcde////int num1 = Fr.read (ch);//Store the read character in an array//system.out.println (num1+": "+new String (CH)) //1:fbcde////here is equivalent to, f the original array of a replaced, and txt no data, so the remaining array elements are still////int num2 = Fr.read (ch);//re-read no data, so return -1,char array no overwrite// System.out.println (num2+ ":" +new String (CH)),//-1:fbcde//normal notation int num = 0; char[] ch = new char[5];//The length of the array is preferably 1024*nwhile ((num = fr.read (ch))!=-1) {System.out.println (new String (Ch,0,num));} Fr.close ();}}


Java Learning lesson 47th-io Stream (a): Read and write files

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.