Reading and writing of files in java and reading and writing in java

Source: Internet
Author: User

Reading and writing of files in java and reading and writing in java

// First, a file is used to store the File to be read. File f = new file ("c:/test/aa.txt"); // when instantiating an input stream, upload the file object to FileInputStream inputStream = new FileInputStream (f); // define a byte array to store the read content byte [] B = new byte [(int) f. length ()]; int len = 0; int temp = 0; while (temp = inputStream. read ())! =-1) {B [len] = (byte) temp; len ++;} System. out. println (new String (B, 0, len, "GBK"); inputStream. close ();

The above is the reading of the file. There is a testfile under the C drive with aa.txt in it.

The last printed content is nishiwodexiaoyaxiaopingguo and zenmekanyekandougouhonghongdexiaolianwennuanwodexnwo.

Write the following files

OutputStream outputStream=new FileOutputStream(f);byte [] bf={'k','u','i'};outputStream.write(bf);outputStream.close();

However, there is a problem with this writing method. He will overwrite the content in the previous file. Therefore, it depends on your own needs. The following code will not be overwritten.

If you don't want to overwrite the content in the file, but you want to append the content on the basis of the original text, you just need to use the following method when instantiating outputStream.

OutputStream outputStream=new FileOutputStream(f,true);

 

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.