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