나는 한 줄에 4 바이트의 A-D에 이르는 4194304 자의 텍스트 파일을 가지고 있습니다. 임의로 문자를 가리키고 다음 문자 집합을 100 자 길이의 다른 파일로 바꾸고 파일에 쓰려면 어떻게해야합니까? 저는 실제로이 작업을 수행 할 수 있지만 여러 번 반복 할 때 실제로 비효율적이라고 느낍니다.파일 읽기 및 임의의 문자 위치에 텍스트 추가
는 여기에 내가 위에서 언급 한 것의 그림이다 : Link to Imageshack
가 여기에 현재이를 달성하고있어 방법은 다음과 같습니다
Random rnum = new Random();
FileInputStream fin = null;
FileOutputStream fout = null;
int count = 10000;
FileInputStream fin1 = null;
File file1 = new File("fileWithSet100C.txt");
int randChar = 0;
while(cnt > 0){
try {
int c = 4194304 - 100;
randChar = rnum.nextInt(c);
File file = new File("file.txt");
//seems inefficient to initiate these guys over and over
fin = new FileInputStream(file);
fin1 = new FileInputStream(file1);
//would like to remove this and have it just replace the original
fout = new FileOutputStream("newfile.txt");
int byte_read;
int byte_read2;
byte[] buffer = new byte[randChar];
byte[] buffer2 = new byte[(int)file1.length()]; //4m
byte_read = fin.read(buffer);
byte_read2 = fin1.read(buffer2);
fout.write(buffer, 0, byte_read);
fout.write(buffer2, 0, byte_read2);
byte_read = fin.read(buffer2);
buffer = new byte[4096]; //4m
while((byte_read = (fin.read(buffer))) != -1){
fout.write(buffer, 0, byte_read);
}
cnt--;
}
catch (...) {
...
}
finally {
...
}
try{
File file = new File("newfile.txt");
fin = new FileInputStream(file);
fout = new FileOutputStream("file.txt");
int byte_read;
byte[] buffer = new byte[4096]; //4m
byte_read = fin.read(buffer);
while((byte_read = (fin.read(buffer))) != -1){
fout.write(buffer, 0, byte_read);
}
}
catch (...) {
...
}
finally {
...
}
감사를 읽어!
편집 :
String stringToInsert = "insertSTringHERE";
byte[] answerByteArray = stringToInsert.getBytes();
ByteBuffer byteBuffer = ByteBuffer.wrap(answerByteArray);
Random rnum = new Random();
randChar = rnum.nextInt(4194002); //4MB worth of bytes
File fi = new File("file.txt");
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(fi, "rw");
} catch (FileNotFoundException e1) {
// TODO error handling and logging
}
FileChannel fo = null;
fo = raf.getChannel();
// Move to the beginning of the file and write out the contents
// of the byteBuffer.
try {
outputFileChannel.position(randChar);
while(byteBuffer.hasRemaining()) {
fo.write(byteBuffer);
}
} catch (IOException e) {
// TODO error handling and logging
}
try {
outputFileChannel.close();
} catch (IOException e) {
// TODO error handling and logging
}
try {
randomAccessFile.close();
} catch (IOException e) {
// TODO error handling and logging
}
안녕 퀀텀, 나는 그것을 들여다 보았지만 1.7이 필요한 것 같습니다. 불행히도, 전환하면 다른 모든 수입을 잃게됩니다. – bigbitecode
"다른 모든 수입품을 잃어 버림"이란 무엇을 의미합니까? 또한, 비록 그들이 비난 되어도 당신이 그들을 사용할 수 없다는 것을 의미하지는 않습니다. – QuantumMechanic
죄송합니다. "다른 모든 수입품"에 대한 나의 실수. 조언 해 주셔서 감사 드리며, RandomAccessFile을 살펴 보겠습니다. – bigbitecode