Io stream-writing and reading of Files

Source: Internet
Author: User

1. File writing

Class:

Filewriter is inherited from writer (the other is Reader)

Method:

Writer (parameter). Based on the parameter, you can write a part of the character, character array, character array, integer, string, and string, and throw ioexception

Flush (); refresh the memory and write the swap stream in the memory to the file.

Close (); refresh the memory and close the character input stream, throwing an ioexception

Import Java. io. *; Class test {public static void main (string [] ARGs) {// This Is A implicit call to the close () method introduced in jdk1.7, filewriter throws ioexception at creation. Try (filewriter = new filewriter ("test.txt") {filewriter. write ("hello");} catch (exception e) {e. printstacktrace () ;}}/ * this is not a new way to write, it is very tedious filewriter = NULL; try () {filewriter = new filewriter ("test.txt"); filewriter. write ("hello");} catch (exception e) {e. printstacktrace ();} finally {try () {filewriter. close ();} catch (exception e) {e. printstacktrace ();}}*/

Note: When filewriter is created, if the file exists, create an empty file with the same name to overwrite it. If the file does not exist, use the constructor to add it.

Filewriter = new filewriter ("file name", true); set to true.

2. File Reading

Class:

Filereader inherits from Reader and Java. Io package

Method:

Read (parameter); can read a single character, can read the character array, can also read part of the character array

Close (); close the character input stream

Code example:

Class test {public static void main (string [] ARGs) {// filereader constructor creates a character input stream try (filereader = new filereader ("test.txt") associated with the Read File ")) {char [] charfile = new char [1024]; int charnum = filereader. read (charfile); system. out. print (new string (charfile, 0, charnum);} catch (ioexception e) {e. printstacktrace ();}}}

 

Io stream-writing and reading of 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.