ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.RandomAccessFile;ImportJava.io.SequenceInputStream;ImportJava.util.Vector; Public classRandonfileaccesstest { Public Static voidMain (string[] args)throwsIOException {Splitfile ("Test.txt"); Mergefile (); MergeFile2 (); }//Split file Public Static voidSplitfile (String Path)throwsioexception{InputStream is=NewFileInputStream (path); intLen=0; byte[] Buff =New byte[1024]; inti = 1; while(Len=is.read (Buff))!=-1) {Randomaccessfile RAF=NewRandomaccessfile ("RAF" +i+ ". txt", "RW");//Raf1.txt Raf2.txt Altogether only two filesRaf.write (buff,0, Len); Raf.close (); I++; } is.close (); }
Merging Files Public Static voidMergefile ()throwsioexception{Randomaccessfile RAF=NewRandomaccessfile ("Raf3.txt", "RW"); InputStream is=NULL; for(inti=1;i<3;i++){ intLen=0; is=NewFileInputStream ("RAF" +i+ ". txt"); It's two files in total .byte[] Buff =New byte[1024]; while(Len=is.read (Buff))!=-1) {raf.write (buff,0, Len); }} is.close (); Raf.close (); }
Another way to merge files Public Static voidMergeFile2 ()throwsioexception{Randomaccessfile RAF=NewRandomaccessfile ("Raf4.txt", "RW"); InputStream is=NULL; Vector<InputStream> VT =NewVector<inputstream>(); for(inti=1;i<3;i++) { is=NewFileInputStream ("RAF" +i+ ". txt");//raf1.txt raf2.txtvt.addelement (IS); } sequenceinputstream sis=NewSequenceinputstream (Vt.elements ()); intLen=0; byte[] Buff =New byte[1024]; while(Len=sis.read (Buff))!=-1) {raf.write (buff,0, Len); } sis.close (); Is.close (); Raf.close (); }}
Randomaccessfile splitting and merging of files