1 Package com.abin.facade.ws.mail.function;2 3 import Java.io.BufferedReader;4 import Java.io.File;5 import Java.io.FileOutputStream;6 import Java.io.FileReader;7 import Java.io.RandomAccessFile;8 9 Public classFileOperation {Ten One /** A * Create a file - * @param fileName - * @return the */ - Public Staticboolean createFile (File fileName) throws exception{ -Boolean flag=false; - Try{ + if(!filename.exists ()) { - filename.createnewfile (); +flag=true; A } at}Catch(Exception e) { - e.printstacktrace (); - } - return true; - } - in /** - * Read txt file contents to * @param fileName + * @return - */ the Public StaticString readtxtfile (File fileName) throws exception{ *String result=NULL; $FileReader filereader=NULL;Panax NotoginsengBufferedReader bufferedreader=NULL; - Try{ theFilereader=NewFileReader (fileName); +Bufferedreader=NewBufferedReader (filereader); A Try{ theString read=NULL; + while((Read=bufferedreader.readline ())! =NULL){ -Result=result+read+"\ r \ n"; $ } $}Catch(Exception e) { - e.printstacktrace (); - } the}Catch(Exception e) { - e.printstacktrace ();Wuyi}finally{ the if(bufferedreader!=NULL){ - bufferedreader.close (); Wu } - if(filereader!=NULL){ About filereader.close (); $ } - } -System. out. println ("the contents of the file read are:"+"\ r \ n"+result); - returnresult; A } + the - Public Staticboolean writetxtfile (String content,file fileName) throws exception{ $Randomaccessfile mm=NULL; theBoolean flag=false; theFileOutputStream o=NULL; the Try { theo =NewFileOutputStream (fileName); -O.write (Content.getbytes ("GBK")); in o.close (); the //mm=new randomaccessfile (fileName, "RW"); the //mm.writebytes (content); Aboutflag=true; the}Catch(Exception e) { the //Todo:handle Exception the e.printstacktrace (); +}finally{ - if(mm!=NULL){ the mm.close ();Bayi } the } the returnFlag; - } - the the the Public Static voidcontenttotxt (String filePath, string content) { theString str =NewString ();//Original TXT content -String S1 =NewString ();//Content Updates the Try { theFile f =NewFile (filePath); the if(F.exists ()) {94System. out. Print ("File exists"); the}Else { theSystem. out. Print ("file does not exist"); theF.createnewfile ();//does not exist then creates98 } AboutBufferedReader input =NewBufferedReader (NewFileReader (f)); - 101 while(str = input.readline ())! =NULL) {102S1 + = str +"\ n";103 }104System. out. println (S1); the input.close ();106S1 + =content;107 108BufferedWriter output =NewBufferedWriter (NewFileWriter (f));109 Output.write (S1); the output.close ();111}Catch(Exception e) { the e.printstacktrace ();113 the } the } the 117}
JAVA Create txt file, write the contents of the file, read the contents of the file