Java IO Read Write file

Source: Internet
Author: User

Java read txt file, Chinese characters garbled, because the encoding format of the file and the program code adopted a different encoding format. Usually, if you do not modify, the encoding format used by Windows itself is GBK (while GBK and gb2312 are basically the same encoding), the program generally uses utf-8, so it is best to specify the encoding method when reading the file

Mode 1: Read and write by Byte stream

ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;ImportJava.io.Writer;Importorg.apache.commons.lang3.StringUtils; Public classFileReadWriteDemo2 { Public Static voidMain (string[] args)throwsIOException {BufferedReader Read=NewBufferedReader (NewInputStreamReader (NewFileInputStream ("F:/test.txt"), "GBK")); Writer out=NewOutputStreamWriter (NewFileOutputStream ("F:/testnew.txt"), "GBK"); BufferedWriter writer=NewBufferedWriter (out); String filecontent=""; String Line= "";  while(line = Read.readline ())! =NULL) {            //Remove Spaces            if(Stringutils.isnotblank (line)) {//System.out.println (line);Filecontent +=line+ "\ r \ n";                Writer.write (line); Writer.write ("\ r \ n");        }} read.close ();        Writer.close ();    System.out.println (filecontent); }}

Mode 2: Read and write with character stream

 Public classFilereadwritedemo { Public Static voidMain (string[] args)throwsIOException {BufferedReader Read=NewBufferedReader (NewFileReader ("F:\\test.txt")); BufferedWriter writer=NewBufferedWriter (NewFileWriter ("F:/testnew.txt")); String Line= "";  while(line = Read.readline ())! =NULL) {                    if(Stringutils.isnotblank (line)) {System.out.println (line);                Writer.write (line); Writer.write ("\ n");        }} read.close ();    Writer.close (); }}

Java IO Read Write file

Related Article

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.