public class MycopyTest {
public static void main(String[] args) {
File src = new File( "D:/1.jpg" );
// D:/1.jpg必須的存在不然會報錯
File dest = new File( "D:/2.jpg" );
// 如果D:/2.jpg存在則覆蓋,如果不存在則建立
streamCopy(src, dest);
}
private static void readCopy(File src,File dest)
{
FileReader fr= null ;
FileWriter fw= null ;
BufferedReader br= null ;
BufferedWriter bw= null ;
try {
fr= new FileReader(src);
fw= new FileWriter(dest);
br= new BufferedReader(fr);
bw= new BufferedWriter(fw);
String str;
while ((str=br.readLine())!= null )
{
bw.write(str);
bw.newLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bw.close();
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void streamCopy(File src, File dest) {
FileInputStream fis = null ;
FileOutputStream fos = null ;
BufferedInputStream bis = null ;
BufferedOutputStream bos = null ;
try {
fis = new FileInputStream(src);
fos = new FileOutputStream(dest);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
int len;
byte [] b = new byte [ 1024 ];
while ((len = bis.read(b)) != - 1 ) {
bos.write(b, 0 , len);
// bos.write(b,0,len);是把讀到數組的大小位元組寫入
// bos.write(b);最後一次如果數組未寫滿的話就會多讀。
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos.close();
bis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|