How to read the contents of a file and assign a value to the corresponding variable in Java

Source: Internet
Author: User

Statement: The article is a personal learning experience, but also a subjective summary, the content is for reference only.

The process of reading and assigning the contents of a file to a variable is mainly in the following steps:

1. Read the file into memory

2. Output the in-memory information to the corresponding variable

As long as the process is understood, the code is simple to implement, and we need a file input stream (FileInputStream), a memory buffer, and a memory output stream (Bytearrayoutputstream). Therefore, we will follow the following steps to write the program:

1. Create a file input stream

2. Create a file input buffer

3. Read the file into the buffer

4. Create a memory output stream

5, the memory storage information output to each variable

File File = new file (c:/config.txt); FileInputStream fis = new FileInputStream (file); Create file input stream byte[] buffer = new byte[1024]; Create file input buffer bytearrayoutputstream bos = new Bytearrayoutputstream (); Create memory output stream int len;while ((len=fis.read (buffer))!=-1) {//when the entire loop ends, the contents of the file are all written to the buffer Bos.write (Buffer,0,len);} Byte[] result = Bos.tobytearray (); The read content is put into a byte array by a memory output stream, String content = new string (result); The contents of the file are assigned to the content variable by storing the result of the data in the character type.


This article is from the "Zhang Hai Warehouse Technology blog" blog, make sure to keep this source http://zhanghaicang.blog.51cto.com/7334247/1599406

How to read the contents of a file and assign a value to the corresponding variable in Java

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.