Today made the Java file read and write, oneself also summed up a bit, but not all, only two ways, first directly look at the code:
Public Static voidMain (string[] args)throwsIOException {io (); Buffer ();}/*** Read and write as a stream can use any file, especially binary files * *@authorhh * @date 2014-12-11 *@throwsIOException*/ Public Static voidIo ()throwsIOException {String fname= "C:/users/administrator/desktop/t.jar"; String fname2= "C:/users/administrator/desktop/t2.rar"; File File=NewFile (fname); File file2=NewFile (fname2); FileInputStream in=Newfileinputstream (file); FileOutputStream out=NewFileOutputStream (file2); byte[] bytes=New byte[2048]; intK = 0; while((K=in.read (bytes))!=-1) {out.write (bytes); /*for (int i = 0; i < bytes.length; i++) {//Such efficiency is very low out.write (Bytes[i]); }*/ } /*or * int b = 0; while ((B=in.read ())!=-1) {out. Write (b); } */Out.close (); In.close (); System.out.println ("End"); } /*** Read and write in the form of a character text file * Not applicable to binary files such as compression and so on the file will be larger than the source file *@authorhh * @date 2014-12-11 *@throwsIOException*/ Public Static voidBuffer ()throwsIOException {String fname= "C:/users/administrator/desktop/1234.txt"; String fname2= "C:/users/administrator/desktop/kk.txt"; File File=NewFile (fname); InputStreamReader Read=NewInputStreamReader (NewFileInputStream (file), "GBK");//solve Chinese garbled characters//FileReader read = new FileReader (file); can also directly use FileReader but will be out of the Chinese garbledFileWriter FW =NewFileWriter (fname2); BufferedReader BufferedReader=NewBufferedReader (read); BufferedWriter b=NewBufferedWriter (FW); String s=NULL; while((s = bufferedreader.readline ())! =NULL) {System.out.println (s); B.write (s); B.newline ();//line BreakB.flush (); } b.close (); Read.close (); Fw.close (); System.out.println ("---end"); }
The first is the use of FileInputStream and FileOutputStream, which is the direct use of IO stream to read data. No matter what documents can be done. But the drawback is that you do not have to read the IO operation once, if the file is large, sales are very low.
The second is the use of BufferedReader and Bufferedwrite. The difference from the previous is that the cache is used, and the characters are read (fileinputstream is bytes). So before using BufferedReader and bufferedwrite to copy a compressed file, the copied file is always twice times the size of the original file.
Two ways to read and write Java files