1. import java.io.*;
    2. /**
    3. * 对接流
    4. */
    5. public class DockingStream {
    6. //文件通过文件字节输入流转换为字节数组后通过字节数组输出流输出到字节数组中
    7. public byte[] fileToByteArray(String FilePath) throws IOException {
    8. byte[] flush = new byte[1024*10];//缓冲容器
    9. int len = -1;//辅助变量,显示缓冲容器当前的长度
    10. File url = new File(FilePath);//确定源
    11. InputStream Is = null;
    12. ByteArrayOutputStream Baos;
    13. try{
    14. //确定流
    15. Is = new FileInputStream(url);
    16. Baos = new ByteArrayOutputStream();
    17. //操作
    18. while((len = Is.read(flush)) != -1){
    19. Baos.write(flush,0,len);
    20. }
    21. Baos.flush();
    22. return Baos.toByteArray();
    23. } catch (IOException e) {
    24. e.printStackTrace();
    25. }finally {
    26. //释放资源
    27. assert Is != null;
    28. Is.close();
    29. }
    30. return null;
    31. }
    32. //字节数组输入流接收到字节数组后通过文件字节输出流将字节数组输出为文件
    33. public void bytearrayToFile(byte[] src, String FilePath) throws IOException {
    34. byte[] flush = new byte[1024*10];//缓冲容器
    35. int len = -1;//辅助变量,显示缓冲容器当前的长度
    36. File url = new File(FilePath);//确定源
    37. OutputStream Os = null;
    38. ByteArrayInputStream Bais;
    39. //确定流
    40. try {
    41. Os = new FileOutputStream(url);
    42. Bais = new ByteArrayInputStream(src);
    43. while((len = Bais.read(flush)) != -1){
    44. Os.write(flush,0,len);
    45. }
    46. Os.flush();
    47. } catch (IOException e) {
    48. e.printStackTrace();
    49. }finally {
    50. assert Os != null;
    51. Os.close();
    52. }
    53. }
    54. }

    主类

    1. import java.io.IOException;
    2. public class Main {
    3. public static void main(String[] args) throws IOException {
    4. DockingStream ds = new DockingStream();
    5. byte[] datas = ds.fileToByteArray("C:\\Users\\DaluxC\\Desktop\\新建文件夹δ\\sunflower.png");
    6. ds.bytearrayToFile(datas, "F:\\Java\\IO Study 04\\src\\sunflower.png");
    7. }
    8. }