나는 txt 파일 안의 문자열을 검색하고 그 위에 특정 내용을 삽입하려고합니다. 슬프게도 출력물이 내가 예상했던 것과 상당히 다른 것처럼 보입니다.
누군가 내게 힌트를 줄 수 있습니까?
이것은 내가 얻은 것입니다.
파일의 문자열을 검색하고 위에 내용을 삽입하십시오.
String description= "filename.txt";
String comparison=" return model;";
RandomAccessFile output = null;
try
{
output = new RandomAccessFile(description, "rw");
String line = null;
while ((line = output.readLine()) != null) {
if (line.equals(comparison)){
//System.out.println("alt: "+line);
output.seek(output.getFilePointer()-line.getBytes().length);
output.writeChars("new stuff; \n");
//System.out.println("new: "+output.readLine());
}
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (output != null){ try { output.close(); } catch (IOException e) { e.printStackTrace(); }}
}
이 내가 읽으려고하는 파일입니다 :
/*filename.txt*/
some longer content ~ 100kB
return model;
further content
을이 나는 내용의 삽입 또는 삭제를 지원하지 않는
/*filename.txt*/
some longer content ~ 100kB
new stuff;
return model;
further content
그리고 실제로 어떻게 되나요? – breezee
이것은 당신이 가지고있는 것입니다. 그것이 당신이 기대하는 것입니다. 그러나 당신은 무엇을 얻고 있습니까? –
두 개의 파일을 사용하십시오. 원하는 파일을 새로운 파일로 복사하십시오. 새 줄을 추가하십시오. 그런 다음 나머지 행을 파일로 다시 복사하십시오. 마지막으로 새 파일의 전체 내용을 이전 파일로 복사하십시오. –