1 using Filereader,filewriter can only achieve the text file copy, and Fileinputstream,fileoutputstream difference is that the reading is the char type of data
2 for non-text files (video files, audio, pictures, etc.), you can only use the byte stream
Packagelianxi1;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException;ImportJava.io.InputStream;Importorg.junit.Test; Public classTestfileinputstream {@Test//the file to be read must exist Public voidtest1 () {FileInputStream fis=NULL; Try{File file1=NewFile ("D:\\io\\helloworld.txt"); FIS=NewFileInputStream (FILE1); intb =Fis.read (); while(B!=-1) {System.out.print (Char) b); b=Fis.read (); } } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } finally{ Try{fis.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } }} @Test//the file to be read must exist Public voidtest2 () {FileInputStream fis=NULL; Try{File file1=NewFile ("D:\\io\\helloworld.txt"); FIS=NewFileInputStream (FILE1); byte[] B =New byte[6]; intLen;//int len = Fis.read (b);//While (len! =-1) {//for (int i=0;i<len;i++) {//System.out.print ((char) b[i]);// }//len = fis.read (b);// } while((Len=fis.read (b))! =-1) {//Note B is a buffer that stores data, and Len is the total number of bytes that return read-in buffers//so Len<=b.length for(inti=0;i<len;i++) {//It's Len, not b.length.System.out.print ((Char) b[i]); } } } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } finally { Try{fis.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }} Packagelianxi1;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;Importorg.junit.Test; Public classTestfileoutputstream {@Test//the file to be written does not have to exist, does not exist and can be created, and the content will be overwritten . Public voidtest1 () {FileOutputStream fos=NULL; Try{File file1=NewFile ("Goodmood"); FOS=NewFileOutputStream (FILE1); Fos.write (NewString ("A good night!"). GetBytes ()); } Catch(Exception e) {e.printstacktrace (); } finally{ Try{fos.close (); } Catch(IOException e) {e.printstacktrace (); } }} @Test//read data from one file, write to another file Public voidtest2 () {FileInputStream fis=NULL; FileOutputStream Fos=NULL; Try{File file1=NewFile ("D:/io/helloworld.txt"); File file2=NewFile ("Goodmood"); FIS=NewFileInputStream (file2); FOS=NewFileOutputStream (FILE1); intLen; byte[] B =New byte[4]; while(len = Fis.read (b))!=-1) {Fos.write (b,0, Len); } }Catch(Exception ex) {ex.printstacktrace ();} finally{ if(fis!=NULL){ Try{fis.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } if(fos!=NULL){ Try{fos.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }}}
Four node streams