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

Source: Internet
Author: User
Tags throw exception

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

IO streams often use base classes

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: Assume that the text form of the data should give priority to the character stream, and the data from memory written to the hard disk 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{//assumes that the file does not exist. Will voluntarily create, exist. Will overwrite FileWriter fw = new FileWriter ("Demo.txt");//Throw exception//Call write method in writer, writing data, but in fact the data is written to the temporary storage buffer fw.write ("hello");// Flushes the buffer of the stream with the Flush method.

Assuming that the stream has saved all the characters of the various write () methods in the buffer, they are written to the intended target immediately. Fw.flush ();//ability to use multiple//close resources//Close the stream, close the resource, call flush to refresh the data in the buffer before closing to the destination//API document: Close the stream, but refresh it first.

After the stream is closed. Calling write () or flush () again will cause the ioexception to be thrown. Closing a previously closed stream is invalid. Fw.close ();//can only be used once}}

Ps:filewriter Constructor FileWriter ("Damo.txt", true), write data, do not write, default is False, overwrite the original data


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 the 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, to infer 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);//Assume that an address that is not found will throw two exceptions//cannot find a file exception, null pointer exception. So the finally part. Add an inference 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), assuming that the end of the stream has been 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 ();}}


Read (); reads a single character. In contrast, 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/* * Create a character array first.  *///char ch[] = new Char[5];//int num = fr.read (ch);//Store The read characters in an array, num is the number of characters//system.out.println (num+ ":" +new String (ch));//5:abcde////int num1 = Fr.read (ch);//Store The read characters in the array//system.out.println (num1+ ":" +new String (CH));//1: fbcde////here is the equivalent. F replaces the A in the original array. There is no data in txt, so the remaining array elements are still////int num2 = Fr.read (ch);//re-read no data. So the return -1,char array has 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.