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);