java 讀寫文件

@Test
public void read() throws Exception {

    String source = "C:\\Users\\Administrator\\Desktop\\167.png";
    String destination = "C:\\Users\\Administrator\\Desktop\\ssss.jpg";

    int bufferSize = 4096; // 設置緩衝區大小
    byte buffer[] = new byte[bufferSize]; // 緩衝區字節數組

    File sourceFile = new File(source);

    InputStream fis = new FileInputStream(sourceFile);

    BufferedInputStream bis = new BufferedInputStream(fis, bufferSize);

    OutputStream fos = new FileOutputStream(destination);
    BufferedOutputStream bos = new BufferedOutputStream(fos, bufferSize);

    long fileSize = sourceFile.length(); // 文件總字節數
    int haveRead = 0; // 已讀取字節數
    int readSize = -1; // 記錄每次實際讀取字節數
    while (null != bis && (readSize = bis.read(buffer)) != -1) {
        haveRead += readSize;
        System.out.println(new String(buffer));

        bos.write(buffer, 0, readSize);
        System.out.println("已經複製:  " + haveRead + " Byte       完成" + haveRead * 100 / fileSize + "%     單次讀取:" + readSize + " Byte");
    }
    bos.flush();
    bos.close();
    bis.close();
    System.out.println("複製完成:  " + haveRead);
}
相關文章
相關標籤/搜索