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