Monday, August 20, 2007

파일읽기쓰기

ㅋㅋㅋㅋ 잘했죠?

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.ByteBuffer.*;

public class Buffer {

static long filesize = 0;
static int divSize = 128;
static int pieceIndex = 0;
static FileChannel InputChannel = null;
static FileChannel OutputChannel = null;
static RandomAccessFile InputFile;
static RandomAccessFile OutputFile;

public static void makebuffer(FileChannel InputChannel,FileChannel OutputChannel,int position,int count)throws Exception{

ByteBuffer buf = ByteBuffer.allocate(divSize);
InputChannel.position(position);
InputChannel.read(buf);
buf.flip();

byte[] by = new byte[buf.limit()];
buf.get(by);
System.out.println(count + "번째 읽어온 부분:" + "\n" + new String(by) + "\n");

ByteBuffer buf2 = ByteBuffer.allocate(divSize);
buf2.put(by);
buf2.flip();
OutputChannel.position(position);
OutputChannel.write(buf2);

}

public static void read_write(RandomAccessFile InputFile ,RandomAccessFile OutputFile) throws Exception{

InputChannel = InputFile.getChannel();
OutputChannel = OutputFile.getChannel();

filesize = InputFile.length();
pieceIndex = (int)filesize/divSize;

if((int)filesize%divSize != 0){
pieceIndex = pieceIndex + 1;
}

System.out.println("fileSize :" + filesize + "\n" + "pieceIndex : " + pieceIndex + "\n" );

int position = 0;

for(int i = 0;i-pieceIndex;i++){
makebuffer(InputChannel,OutputChannel,position,i+1);
position += divSize;
}

}

public static void main(String[] args) throws Exception {
String filename = "C:\\workspace\\RandomAccess\\src\\a.txt";
String filename2 = "C:\\workspace\\RandomAccess\\src\\copy_a.txt";

try {
InputFile = new RandomAccessFile(filename,"rw");
OutputFile = new RandomAccessFile(filename2,"rw");

read_write(InputFile,OutputFile);

} catch(IOException ex) {
ex.printStackTrace();
} finally {
try {
InputChannel.close();
OutputChannel.close();
InputFile.close();
OutputFile.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}

1 comment:

mn said...

read_write함수에서요
for 문에서
int i+0;i부등호pieceIndex;i++
이건데 부등호 이 기호때문에 자꾸 그부분이 지워져요.. 그래서 - 표시로 해놨으니
- 이걸 부등호 로 바꿔주셔요..ㅋㅋㅋ
그럼 안녕히...ㅋㅋ