文件分段读取示例,分段读取示例,package my.t
分享于 点击 15017 次 点评:176
文件分段读取示例,分段读取示例,package my.t
package my.test;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.RandomAccessFile;public class ImageFileCopy { /** * @param args */ public static void main(String[] args) { String prePath = "D:\\\\testFile\\\\test.jpg"; String curPath = ""; copyImgFile(prePath, curPath); } /** * 文件图像文件 * @param prePath 图片之前存放路径 * @param curPath 图片拷贝之后存放路径 */ private static void copyImgFile(String prePath, String curPath) { long segmentLength = 1024 * 1024; //1M大小 try { RandomAccessFile randomAccessFile = new RandomAccessFile(prePath, "r"); File tempFile = new File("D:\\\\testFile\\\\", "temp.jpg"); FileOutputStream fileOutputStream = new FileOutputStream(tempFile, true); int currentSegment = 0; int count = (int)(randomAccessFile.length() / segmentLength ) + (randomAccessFile.length() % segmentLength > 0 ? 1 : 0); for(int i = 0; i < count; i++) { currentSegment = i + 1; System.out.println("分段:" + currentSegment); randomAccessFile.seek(i * segmentLength); long toal = 0; //当前已读取的长度 int read = 0; //一次读取的长度 int bufferLenght = 500 * 1024; //缓存长度 byte[] buffer = new byte[bufferLenght]; while ((read = randomAccessFile.read(buffer, 0, bufferLenght)) > 0) { System.out.println("bufferLength:" + bufferLenght); fileOutputStream.write(buffer, 0, read); toal += read; bufferLenght = (int) ((toal + bufferLenght) > segmentLength ? segmentLength - toal : bufferLenght); } /*long toal = 0; //当前已读取的长度 int read = 0; //一次读取的长度 int bufferLenght = 500 * 1024; //缓存长度 int bufferLenghtTemp = bufferLenght; byte[] buffer = new byte[bufferLenght]; while ((read = randomAccessFile.read(buffer, 0, bufferLenght)) > 0) { fileOutputStream.write(buffer, 0, read); toal += read; //bufferLenght = (int) ((toal + bufferLenght) > segmentLength ? segmentLength - toal : bufferLenght); if(toal >= segmentLength) break; else { if((toal + bufferLenghtTemp) >= segmentLength) bufferLenght = bufferLenghtTemp; else bufferLenght = (int) (bufferLenghtTemp - toal); } }*/ } fileOutputStream.flush(); fileOutputStream.close(); System.out.println("源文件大小:" + randomAccessFile.length() + " , 拷贝后文件大小:" + tempFile.length()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}//该片段来自于http://byrx.net
用户点评