java_IO_位元組碼(二進位制)檔案複製
阿新 • • 發佈:2021-01-18
我這裡只是提供簡單的成品程式碼,不明白的點請看我前面寫的有關IO的基礎知識,通常使用“程式碼2”
程式碼1(節點流):
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFile {
public static void main(String[] args) {
File f1 = new File("src/foryou/IO/check.jpg");
File f2 = new File("src/foryou/IO/check_copy.jpg");
FileInputStream in =null;
FileOutputStream out =null;
try {
in = new FileInputStream(f1);
out = new FileOutputStream(f2);
byte []b =new byte[10];
int len;
while((len = in.read (b)) != -1) {
out.write(b, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("image is completed");
}
}
程式碼2(緩衝流):
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileIn_OutputStreamCopyFile {
public static void main(String[] args) {
File f1 = new File("src/foryou/IO/check.jpg");
File f2 = new File("src/foryou/IO/check_copy.jpg");
BufferedInputStream bin =null;
BufferedOutputStream bout =null;
try {
bin = new BufferedInputStream(new FileInputStream(f1));
bout = new BufferedOutputStream(new FileOutputStream(f2));
byte []b =new byte[10];
int len;
while((len = bin.read(b)) != -1) {
bout.write(b, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(bout != null) {
bout.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bin != null) {
bin.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("image is completed");
}
}
結果: