文本文件使用字符流来处理
非文本文件使用字节流来处理
字节流处理代码整理
public void copyFile(String srcPath, String desPath) {FileInputStream fileInputStream = null;FileOutputStream fileOutputStream = null;try {File srcFile = new File(srcPath);File desFile = new File(desPath);fileInputStream = new FileInputStream(srcFile);fileOutputStream = new FileOutputStream(desFile);byte[] buffer = new byte[1024];int len;while ((len = fileInputStream.read(buffer)) != -1) {fileOutputStream.write(buffer, 0, len);}} catch (IOException e) {e.printStackTrace();} finally {if (fileInputStream != null) {try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}if (fileOutputStream != null) {try {fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}}}
使用缓冲流优化
public void copyFileWithBuffered(String srcPath, String desPath) {FileInputStream fileInputStream = null;FileOutputStream fileOutputStream = null;BufferedInputStream bufferedInputStream = null;BufferedOutputStream bufferedOutputStream = null;try {File srcFile = new File(srcPath);File desFile = new File(desPath);fileInputStream = new FileInputStream(srcFile);fileOutputStream = new FileOutputStream(desFile);bufferedInputStream = new BufferedInputStream(fileInputStream);bufferedOutputStream = new BufferedOutputStream(fileOutputStream);byte[] buffer = new byte[1024];int len;while ((len = bufferedInputStream.read(buffer)) != -1) {bufferedOutputStream.write(buffer, 0, len);}} catch (IOException e) {e.printStackTrace();} finally {if (bufferedInputStream != null) {try {bufferedInputStream.close();} catch (IOException e) {e.printStackTrace();}}if (bufferedOutputStream != null) {try {bufferedOutputStream.close();} catch (IOException e) {e.printStackTrace();}}if (fileInputStream != null) {try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}if (fileOutputStream != null) {try {fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}}}