파일이 매우 큰, 분할 파일 수 있기 때문에 그 자체가 aswell 큰 수 :
예 :
소스 파일 크기 : 5기가바이트
민 분할 : 5 : 대상
파일 크기 : 각 1GB (5 개 파일)
우리는 그런 메모리가 있더라도 한 번에이 큰 분할 청크를 읽을 방법이 없습니다. 기본적으로 각 분할마다 성능과 메모리면에서 실현 가능한 픽스 크기 byte-array
을 읽을 수 있습니다.
NumSplits : 10 MaxReadBytes : 8킬로바이트
public static void main(String[] args) throws Exception
{
RandomAccessFile raf = new RandomAccessFile("test.csv", "r");
long numSplits = 10; //from user input, extract it from args
long sourceSize = raf.length();
long bytesPerSplit = sourceSize/numSplits ;
long remainingBytes = sourceSize % numSplits;
int maxReadBufferSize = 8 * 1024; //8KB
for(int destIx=1; destIx <= numSplits; destIx++) {
BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream("split."+destIx));
if(bytesPerSplit > maxReadBufferSize) {
long numReads = bytesPerSplit/maxReadBufferSize;
long numRemainingRead = bytesPerSplit % maxReadBufferSize;
for(int i=0; i<numReads; i++) {
readWrite(raf, bw, maxReadBufferSize);
}
if(numRemainingRead > 0) {
readWrite(raf, bw, numRemainingRead);
}
}else {
readWrite(raf, bw, bytesPerSplit);
}
bw.close();
}
if(remainingBytes > 0) {
BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream("split."+(numSplits+1)));
readWrite(raf, bw, remainingBytes);
bw.close();
}
raf.close();
}
static void readWrite(RandomAccessFile raf, BufferedOutputStream bw, long numBytes) throws IOException {
byte[] buf = new byte[(int) numBytes];
int val = raf.read(buf);
if(val != -1) {
bw.write(buf);
}
}
while 루프에서 원하는만큼 많은 줄을 String 또는 StringBuilder에 수집하여 별도의 파일에 쓸 수 있습니다. 파일의 최대 줄 수를 정의하기 전에 미리 파일 수를 알 수는 없습니다. –
회선 수를 얻으려면 한 번, 분할하려면 한 번 두 번 반복해야합니다. 또는 선의 수를 추측하고 그런 식으로 나눌 수 있습니다. –
@ kw4nta 지구상에 왜 줄을 꾸미고 싶습니까? 1) OP는 모든 라인을 저장하는 것이 옵션이 아니라고 말합니다. 2) 라인을 다른 파일에 똑바로 작성할 수 있다고 가정하면 ... –