package com.sgcc.controller;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class test {
public static void splitFile(String filePath, int fileCount) throws IOException {
FileInputStream fis = new FileInputStream(filePath);
FileChannel inputChannel = fis.getChannel();
final long fileSize = inputChannel.size();
long average = fileSize / fileCount;//平均值
long bufferSize = 200; //緩存塊大小,自行調整
ByteBuffer byteBuffer = ByteBuffer.allocate(Integer.valueOf(bufferSize + "")); // 申請一個緩存區
long startPosition = 0; //子文件開始位置
long endPosition = average < bufferSize ? 0 : average - bufferSize;//子文件結束位置
for (int i = 0; i < fileCount; i++) {
if (i + 1 != fileCount) {
int read = inputChannel.read(byteBuffer, endPosition);// 讀取數據
readW:
while (read != -1) {
byteBuffer.flip();//切換讀模式
byte[] array = byteBuffer.array();
for (int j = 0; j < array.length; j++) {
byte b = array[j];
if (b == 10 || b == 13) { //判斷\n\r
endPosition += j;
break readW;
}
}
endPosition += bufferSize;
byteBuffer.clear(); //重置緩存塊指針
read = inputChannel.read(byteBuffer, endPosition);
}
}else{
endPosition = fileSize; //最後一個文件直接指向文件末尾
}
FileOutputStream fos = new FileOutputStream(filePath + (i + 1));
FileChannel outputChannel = fos.getChannel();
inputChannel.transferTo(startPosition, endPosition - startPosition, outputChannel);//通道傳輸文件數據
outputChannel.close();
fos.close();
startPosition = endPosition + 1;
endPosition += average;
}
inputChannel.close();
fis.close();
}
public static void main(String[] args) throws Exception {
/*Scanner scanner = new Scanner(System.in);
scanner.nextLine();*/
long startTime = System.currentTimeMillis();
splitFile("C:/Users/dell/Desktop/新建文件夾 (3)/osg-uc0010.log",20);
long endTime = System.currentTimeMillis();
System.out.println("耗費時間: " + (endTime - startTime) + " ms");
//scanner.nextLine();
}
/*public static void main(String[] args) {
ThreadObj obj = new ThreadObj();
Thread t1 = new Thread(obj);
t1.start();
Thread t2 = new Thread(obj);
t2.start();
Thread t3 = new Thread(obj);
t3.start();
}*/
}
/*class ThreadObj implements Runnable{
static int i = 0;
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
while(i<100){
i++;
System.out.println(Thread.currentThread().getName());
}
i = 0;
Thread.yield();
}
}
}*/
java切割打文本文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.