JAVA 47th-IO stream (1): file read/write

Source: Internet
Author: User

JAVA 47th-IO stream (1): file read/write

Input stream and output stream relative to memory

Read data from external devices to memory: Input

Write data in memory to external devices: Output

I/O streams often use base classes

Abstract base class of byte stream: InputStream, OutputStream

Abstract base class of characters: Reader and Writer

PS: The child classes generated by these four schools are suffixed with the parent class name.

For example, FileInputStream, a derived class of InputStream, and FileReader, a derived class of Reader.

PS: for text-based data, ignore streams should be given priority, and data should be written from memory to hard disk as Writer

FileWriter class

Demo: Saving text to a hard disk (FileWriter)

Import java. io. fileWriter; import java. io. IOException; public class Main {public static void main (String [] args) throws IOException {// if the object does not exist, it is automatically created and exists, it will overwrite FileWriter fw = new FileWriter ("Demo.txt"); // throw an exception // call the write method in the Writer to write data, but the data is actually written to the fw in the temporary storage buffer. write ("hello"); // use the flush method to refresh the buffer of the stream. If the stream has saved all the characters of various write () methods in the buffer, it is immediately written to the expected target. Fw. flush (); // you can use it multiple times // close the resource // close the stream to close the resource. Call flush to refresh the data in the buffer to the destination before closing the resource. // API documentation: close the stream, but refresh it first. // After closing the stream, calling write () or flush () will throw an IOException. Disabled previously disabled streams are invalid. Fw. close (); // can be used only once }}

Details

Import java. io. fileWriter; import java. io. IOException; public class Main {private static final String LINE_SEPARATOR = System. getProperty ("line. separator "); public static void main (String [] args) throws IOException {FileWriter fw = new FileWriter (" Demo.txt ", true); // constructor, adding "true" can implement the continued write of the file fw. write ("hello" + LINE_SEPARATOR + "world"); // The line feed in Windows is \ r \ n, and in Linus is \ nfw. write (LINE_SEPARATOR + "ads"); fw. flush (); fw. close ();}}

Basic stream Exception Handling

Create a reference outside try and create an object in it,When disabling the function, you must determine whether it is a null pointer.

Import java. io. fileWriter; import java. io. IOException; public class Main {private static final String LINE_SEPARATOR = System. getProperty ("line. separator "); public static void main (String [] args) {FileWriter fw = null; try {fw = new FileWriter (" z: \ Demo.txt ", true ); // If an unfound address is input, two exceptions will be thrown. // The file exception and NULL pointer exception will not be found. Therefore, in finally part, add a sentence to determine whether it is a null pointer fw. write ("hello" + LINE_SEPARATOR + "world"); fw. flush ();} catch (Exception e) {System. out. p Rintln (e. toString ();} finally {// try again last time to process if (fw! = Null) {try {fw. close () ;}catch (IOException e) {throw new RuntimeException ("failed to close ");}}}}}

FileReader class

Read a text file and print the read data to the console.

Import java. io. fileReader; import java. io. IOException; public class Main {public static void main (String [] args) throws IOException {// ensure that the file is an existing FileReader fr = new FileReader ("g: \ java \ Main \ Demo.txt "); // The file content is the AB // read method, which is used as an integer to read characters ranging from 0 to 65535 (0x00-0xffff ), if the end of the stream is reached,-1 // int c = fr is returned. 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 involves reading arrays in the form of overloading: High Efficiency

Import java. io. fileReader; import java. io. IOException; public class Main {public static void main (String [] args) throws IOException {FileReader fr = new FileReader ("g: \ java \ Main \ Demo.txt "); // The file content is abcdef // use read (char [] a) to read text file data/** create a character array first, * // char ch [] = new char [5]; // int num = fr. read (ch); // store the characters read to the array. num indicates the number of characters. // System. out. println (num + ":" + new String (ch); // 5: abcde // int num1 = fr. read (ch ); // Store the characters to the array. // System. out. println (num1 + ":" + new String (ch); // 1: fbcde // This is equivalent to f replacing a in the original array, the txt file has no data, so the remaining array elements are still in the // int num2 = fr. read (ch); // No data is read again, so-1 is returned, and the char array is not overwritten. // System. out. println (num2 + ":" + new String (ch); //-1: fbcde // 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 ();}}


Related Article

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.