在JDK1.4之前,複製檔案可以利用
(1) FileInputStream
(2) FileOutputStream
(3) read()
這三個關鍵方法來完成,程式如下:
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("/mnt/sdcard/xxx.apk");
fos = new FileOutputStream("/mnt/sdcard/xxx2.apk");
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
if (fis != null) fis.close();
if (fos != null) fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
到了JDK1.4之後,有更具效率的新套件可以用。我們改用FileChannel的方式來實作程式:
FileChannel fis = null;
FileChannel fos = null;
try {
fis = new FileInputStream("/mnt/sdcard/xxx.apk").getChannel();
fos = new FileOutputStream("/mnt/sdcard/xxx2.apk").getChannel();
fos.transferFrom(fis, 0, fis.size());
if (fis != null) fis.close();
if (fos != null) fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
(1) FileInputStream
(2) FileOutputStream
(3) read()
這三個關鍵方法來完成,程式如下:
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("/mnt/sdcard/xxx.apk");
fos = new FileOutputStream("/mnt/sdcard/xxx2.apk");
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
if (fis != null) fis.close();
if (fos != null) fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
到了JDK1.4之後,有更具效率的新套件可以用。我們改用FileChannel的方式來實作程式:
FileChannel fis = null;
FileChannel fos = null;
try {
fis = new FileInputStream("/mnt/sdcard/xxx.apk").getChannel();
fos = new FileOutputStream("/mnt/sdcard/xxx2.apk").getChannel();
fos.transferFrom(fis, 0, fis.size());
if (fis != null) fis.close();
if (fos != null) fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
沒有留言:
張貼留言