java使用IO位元組流讀取複製檔案
阿新 • • 發佈:2018-12-16
具體程式碼如下:
package com.copy; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class reviewio { public static byte[] FileToBytearr(String src) throws Exception{ File src1=new File(src); InputStream is = new FileInputStream(src1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len=-1; byte[] datas=new byte[2048]; while((len=is.read(datas))!=-1){ baos.write(datas, 0, len); } baos.flush(); baos.close(); is.close(); return baos.toByteArray(); } public static void ByteArrToFile(String src,byte[] b) throws Exception{ File src1=new File(src); ByteArrayInputStream bais = new ByteArrayInputStream(b); OutputStream os=new FileOutputStream(src1); int len=-1; byte[] c=new byte[1024]; while((len=bais.read(c))!=-1){ os.write(c, 0, len); }os.flush(); bais.close(); os.close(); } public static void main(String[] args) throws Exception { byte[] a=FileToBytearr("C:/Users/17331/Desktop/poetry.html");//你要複製的檔案的路徑 System.out.println(a.length); ByteArrToFile("C:/Users/17331/Desktop/poetry1.html",a);//你要複製檔案到什麼地方的路徑 } }