日期:2014-05-20  浏览次数:20907 次

请大家帮看看,如何读一个文件,并且备份成两份!
c:/a.gif文件,将a.gif备份成u.gif和b.gif(文件必须读一回)
请问能否使用BufferedInputStream来反复读写内存?

import   java.io.BufferedInputStream;
import   java.io.FileInputStream;
import   java.io.FileOutputStream;
import   java.io.IOException;
import   java.io.OutputStream;

public   class   Test   {

public   static   void   main(String[]   args)   throws   IOException   {

FileInputStream   fis   =   new   FileInputStream( "c:/a.gif ");
BufferedInputStream   snap2bis   =   new   BufferedInputStream(fis);
BufferedInputStream   snap2bis2   =   new   BufferedInputStream(fis);

System.out.println(snap2bis.available());
System.out.println(snap2bis.available());

System.out.println(snap2bis.available());
snap2bis.mark(0);

writefile(snap2bis,   "c:/u.gif ");
System.out.println(snap2bis.available());
snap2bis.reset();
writefile(snap2bis2,   "c:/b.gif ");
System.out.println(snap2bis.available());

snap2bis.close();

}

private   static   void   writefile(BufferedInputStream   bis,   String   filepath)
throws   IOException   {
OutputStream   os   =   new   FileOutputStream(filepath);
int   bytesRead   =   0;
byte[]   buffer   =   new   byte[8192];
while   ((bytesRead   =   bis.read(buffer,   0,   8192))   !=   -1)   {
os.write(buffer,   0,   bytesRead);
}
os.close();
}


}


------解决方案--------------------
我试着写了一下
package aaaa;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.File;

public class shiyan {
public static void main(String[] args) {
try{
File wenjian=new File(args[0]);
File shuchu1=new File(args[1]);
File shuchu2=new File(args[2]);

FileInputStream duqu=new FileInputStream(wenjian);
BufferedInputStream duqua=new BufferedInputStream(duqu);

FileOutputStream xieru1=new FileOutputStream(shuchu1);
FileOutputStream xieru2=new FileOutputStream(shuchu2);

BufferedOutputStream xierua1=new BufferedOutputStream(xieru1);
BufferedOutputStream xierua2=new BufferedOutputStream(xieru2);

byte[] zijie=new byte[1024];

while(duqua.read(zijie)!=-1)
{
xierua1.write(zijie);
xierua2.write(zijie);
}

xierua1.flush();
xierua2.flush();
xierua1.close();
xierua2.close();

duqua.close();
duqu.close();

if (shuchu1.exists() && shuchu1.length()> 0)
System.out.println(args[1]+ "输出成功! ");
else
System.out.println(args[1]+ "输出失败! ");

if (shuchu2.exists() && shuchu2.length()> 0)
System.out.println(args[2]+ "输出成功! ");
else
System.out.println(args[2]+ "输出失败! ");