반응형
파일에 다음과 같은 내용이 있습니다.
aaa
bbb
ccc
ddd
여기서 bbb를 삭제하는 방법은 다음과 같습니다.
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "bbb";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
출처: https://stackoverflow.com/questions/1377279/find-a-line-in-a-file-and-remove-it
728x90
반응형
'back end > java' 카테고리의 다른 글
ClassNotFoundException: JAXBException 해결 방법 (0) | 2023.01.06 |
---|---|
How to append text to an existing file in Java? (0) | 2023.01.01 |
[Spring] MariaDB log4jdbc Cannot create JDBC driver error (2) | 2022.12.22 |
spring 에서 cron scheduler 를 disable 하는 방법 (0) | 2022.12.21 |
spring boot restful api에서 대용량 엑셀 다운로드 (0) | 2022.11.14 |