Java read txt file, newline write TXT file

Source: Internet
Author: User

Java read txt file, newline write TXT file

1. Java Read TXT file

 PackageCom.campu;ImportJava.io.BufferedInputStream;ImportJava.io.BufferedReader;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.InputStreamReader;ImportJava.io.Reader;/*** H20121012.java*/ Public classH20121012 { Public Static voidreadtxtfile (String filePath) {Try{String encoding= "GBK"; File File=NewFile (FilePath); if(File.isfile () && file.exists ()) {//determine if a file existsInputStreamReader Read =NewInputStreamReader (NewFileInputStream (file), encoding);//considering the encoding formatBufferedReader BufferedReader =NewBufferedReader (read); String Linetxt=NULL;  while((Linetxt = Bufferedreader.readline ())! =NULL) {System.out.println (linetxt);        } read.close (); }Else{System.out.println ("The specified file cannot be found"); }        } Catch(Exception e) {System.out.println ("Error reading file contents");        E.printstacktrace (); }         }          Public Static voidMain (String argv[]) {string FilePath= "L:\\apache\\htdocs\\res\\20121012.txt";//"res/";Readtxtfile (FilePath); }           }

2. Write TXT file with different operating systems

For commonly used systems, you can use the following escape character to implement line breaks:
Text file line break under Windows: \ r \ n
Text file line break under Linux/unix: \ r
Text file line break under Mac: \ n

(1). Use the escape character "\ r \ n" in Java:

Java code

String str="AAA";

str+="\ r \ n";

(2). BufferedWriter's NewLine () method:

Java code

FileOutputStream fos=New FileOutputStream ("C;\\11.txt");

BufferedWriter bw=New BufferedWriter (FOS);

Bw.write ("Hello");

Bw.newline ();

Bw.write ("Java");

W.newline ();

Java read txt file, newline write TXT file

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.