그래서 텍스트 파일의 특정 지점에 문자열을 쓰고 싶습니다. 꽤 쉬워야하지만 BufferedWriter 클래스를 처음 사용합니다. 내 소스는 다음과 같습니다 :특정 지점의 텍스트 파일에 무언가 쓰기 Java
public static String readFile(String fileName) throws IOException {
String toReturn = "";
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("test.txt"));
while ((sCurrentLine = br.readLine()) != null) {
toReturn = toReturn+"\n"+sCurrentLine;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return toReturn;
}
public static void addAfter(String toAdd, char after, String fileName) throws IOException {
String file = readFile(fileName);
int length = file.length();
char[] chr = file.toCharArray();
boolean pos[] = new boolean[length];
for(int i = 0; i < length; i++) {
if(chr[i] == after) {
pos[i] = true;
}
}
BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
}
BufferedWriter 클래스를 사용하여 위치 i에 String toAdd를 추가하고 싶습니다. 원하는 포인트로 점프하고 추가로 작성하는 방법은 무엇입니까? 사전에
감사
'RandomAccessFile'에는 파일의 특정 바이트로 점프하는 메소드가 있습니다. 나는 그 방법이'skipBytes()'또는 그와 비슷한 것이라고 생각한다. 그러나 텍스트를 삽입하려고하면 기본적으로 파일 IO가 덮어 쓰기로 처리되므로 다소 까다로울 수 있습니다. 당신이해야 할 일은 그 시점의 원래 파일을 읽고 추가하는 것입니다. – CodeChimp
이 작업을 수행하려면 파일의 내용을 String으로 읽고, 편집으로 새 String을 만든 다음 새 String으로 파일을 덮어 써야한다고 생각합니다. http://stackoverflow.com/questions/3935791/find-and-replace-words-lines-in-a-file을 참조하십시오. – ktm5124
@ ktm5124 링크를 이용해 주셔서 감사합니다. –