1 ImportJava.io.BufferedInputStream;2 ImportJava.io.BufferedOutputStream;3 ImportJava.io.FileInputStream;4 ImportJava.io.FileOutputStream;5 ImportJava.io.InputStream;6 ImportJava.io.OutputStream;7 8 /**9 * Test file read, write, copy functionTen * @package: java05 One * @authorshaobn A * @Describe: Test file read, write, copy function - * @Time: 2015-9-5 pm 10:50:18 - */ the Public classTestcopytext { - Public Static voidMain (string[] args)throwsexception{ - //read files and print -System.out.println (ReadText (NewFileInputStream ("D:\\hello.txt"))); + //write content to file -WRITETEXT (NewFileOutputStream ("D:\\hellocopy.txt"), "Hello, read and write files are generally used character stream, this way is not recommended!" "); + //copy files, write the contents of the file unchanged AWRITETEXT (NewFileOutputStream ("D:\\hellocopy.txt",true), ReadText (NewFileInputStream ("D:\\hello.txt"))); at } - //reading files with FileInputStream - Public StaticString ReadText (InputStream is) { -Bufferedinputstream bis =NULL; -String str =NULL; - Try { inbis =NewBufferedinputstream (IS); - intLen = 0; to byte[] by =New byte[1024]; + while(Len=bis.read (by))!=-1){ -str =NewString (by,0, Len); the } *}Catch(Exception e) { $ //Todo:handle ExceptionPanax Notoginseng e.printstacktrace (); -}finally{ the Try { + if(bis!=NULL){ A bis.close (); the returnstr; + } -}Catch(Exception E2) { $ //Todo:handle Exception $ e2.printstacktrace (); - } - } the returnstr; - }Wuyi //writing files with FileOutputStream the Public Static voidWRITETEXT (outputstream os,string str) { -Bufferedoutputstream BOS =NULL; Wu Try { -BOS =Newbufferedoutputstream (OS); About Bos.write (Str.getbytes ()); $}Catch(Exception e) { - //Todo:handle Exception - e.printstacktrace (); -}finally{ A Try{ + if(bos!=NULL){ the bos.close (); - } $}Catch(Exception e) { the //Todo:handle Exception the e.printstacktrace (); the } the - } in the } the}
Statement: The general reading and writing text files are character stream, the author uses the word stream to write, recommend that you use character stream read and write text files.
Java implementation of file read/write, copy