Used to Python in Java, read the file this really feel trouble, wrote a small piece of code on the Java read and write a simple package, finally comfortable a bit:
Packageseleniumtest;Importjava.io.IOException;ImportJava.io.File;ImportJava.io.FileReader;ImportJava.io.FileWriter;ImportJava.io.BufferedReader;Importjava.util.List;Importjava.util.ArrayList; Public classMyFile { PublicFile F; PublicFileWriter FW; PublicFileReader fr; MyFile (String path) {f=NewFile (path); if(F.exists ()! =true){ Try{f.createnewfile (); }Catch(Exception e) {e.printstacktrace (); } } This. Createwriter (); This. Createreader (); } Private voidCreatewriter () {Try{FW=NewFileWriter (F,true); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Private voidCreatereader () {Try{FR=NewFileReader (f); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } PublicFileWriter getwriter () {returnFW; } PublicBufferedReader Getreader () {bufferedreader br=NewBufferedReader (FR); returnBR; } Public Static voidAppendwriter (String path, list<string>lines) {MyFile tmp=NewMyFile (path); Tmp.createwriter (); FileWriter FW=Tmp.getwriter (); for(String line:lines) {Try{fw.write (String.Format ("%s%s", Line.trim (), "\ r \ n")); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Try{fw.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Public StaticList<string>myreader (String path) {List<String> result =NewArraylist<string>(); MyFile tmp=NewMyFile (path); Tmp.createwriter (); BufferedReader FR=Tmp.getreader (); String s; Try { while((s = fr.readline ())! =NULL) {Result.add (s); } } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } returnresult; }}
View Code
Java Read file