2012-05-20 3 views
0

나는 한 줄에 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

당신은 아마 자바의 랜덤 액세스 파일 기능을 사용하려면 : 호기심 사람들을 위해 , 여기에 내가 상기 문제를 해결하기 위해 사용되는 코드입니다. Sun/Oracle은 아마도 유용 할 Random Access Files tutorial입니다.

Java 7을 사용할 수 없으면 Java 1.0 이후에도 탐색 기능을 가지고 있으며 존재했던 RandomAccessFile을 확인하십시오.

+0

안녕 퀀텀, 나는 그것을 들여다 보았지만 1.7이 필요한 것 같습니다. 불행히도, 전환하면 다른 모든 수입을 잃게됩니다. – bigbitecode

+0

"다른 모든 수입품을 잃어 버림"이란 무엇을 의미합니까? 또한, 비록 그들이 비난 되어도 당신이 그들을 사용할 수 없다는 것을 의미하지는 않습니다. – QuantumMechanic

+0

죄송합니다. "다른 모든 수입품"에 대한 나의 실수. 조언 해 주셔서 감사 드리며, RandomAccessFile을 살펴 보겠습니다. – bigbitecode

-1

먼저 파일에 대해 전역 변수로 파일을 가질 수 있습니다. 파일을 다시 읽지 않고 필요할 때마다 파일을 사용하게됩니다. 또한 새 파일을 만들면 이미 얻은 데이터가 손실됩니다. 예를 들어

:

public class Foo { 

    // Gloabal Vars // 
    File file; 

    public Foo(String location) { 
    // Do Something 
    file = new File(location); 
    } 

    public add() { 
    // Add 
    } 

} 

귀하의 질문에 대답, 내가 먼저 두 파일을 읽은 다음 메모리에 원하는 모든 변경 사항을 만들 것입니다. 모든 변경 작업을 마친 후에 변경 내용을 파일에 기록합니다.

그러나 파일이 매우 큰 경우 디스크의 모든 변경 사항을 하나씩 수행합니다 ... 속도는 느리지 만 메모리 부족은 없습니다. 당신이하는 일에 대해 얼마나 느린지 카운터를 돕기 위해 버퍼를 사용할 수 있을지는 의문입니다.

내 제안은 배열을 사용하는 것입니다. 예를 들어 다음을 수행합니다.

public char[] addCharsToString(String str, char[] newChars, int index) { 
     char[] string = str.toCharArray(); 
     char[] tmp = new char[string.length + newChars.length]; 
     System.arraycopy(string, 0, tmp, 0, index); 
     System.arraycopy(newChars, index, tmp, index, newChars.length); 
     System.arraycopy(string, index + newChars.length, tmp, index + newChars.length, tmp.length - (newChars.length + index)); 
     return tmp; 
} 

희망이 있습니다.