2017-01-16 1 views
1

저는 kotlin을 처음 사용했습니다. 나는 한 줄씩 파일을 읽으려고하고 끝에 각각 뭔가를 추가하려고한다. 읽기 전에줄을 읽고 끝에 무언가를 추가하십시오.

내 파일 :

abcd;abcd;abcd; 
bcda;bcda;bcda; 
dacb;dacb;dacb; 

읽고 추가 후 내 파일 :

abcd;abcd;abcd;smth1 
bcda;bcda;bcda;smth2 
dacb;dacb;dacb;smth3 

내가 라인으로 파일 라인을 읽는 코드를 가지고 있지만 어떻게 각 문자열을 추가하는 나에게 말할 수 그들의?

val pathToFile = "abc.txt" 
val scan = Scanner(File(pathToFile)) 
while (scan.hasNextLine()) { 
    val line = scan.nextLine() 
    var lista = ArrayList<String>() 
    lista = line.split(";") as ArrayList<String> 
    println(lista.get(0) + " and " + lista.get(1) + " and " + lista.get(2)) 
} 

답변

1

RandomAccessFile을 사용하지 않는 한 동일한 파일을 읽고 쓸 수 없습니다. 대신 다음을 수행해야합니다.

  • 입력 파일에서 행을 읽으십시오.
  • 원하는대로 수정하십시오 (행 끝에 추가, 인쇄 행).
  • 수정 된 행을 출력 파일에 씁니다.
  • 모든 데이터를 읽거나 쓰고 나면 두 파일을 모두 닫습니다.
  • 입력 파일을 삭제하십시오. 출력 파일을 입력 파일 이름으로 바꿉니다.
5

Januson은 오른쪽 idea입니다.

inline fun File.mapLines(crossinline transform: (line: String) -> String) { 
    val tempFile = createTempFile(prefix = "transform", suffix = ".txt") 
    tempFile.printWriter().use { writer -> 
     this.forEachLine { line -> writer.println(transform(line)) } 
    } 
    check(this.delete() && tempFile.renameTo(this)) { "failed to replace file" } 
} 

사용 예제는 : 자바 1.7+를 사용하는 경우

val pathToFile = "abc.txt" 
var index = 0 
File(pathToFile).mapLines { line -> "${line}smth${++index}" } 

다음 대신 delete/renameToFiles.move를 사용할 수 있습니다

Files.move(tempFile.toPath(), this.toPath(), StandardCopyOption.REPLACE_EXISTING) 
다음 일을 할 몇 가지 코 틀린 코드입니다

도 참조하십시오. Write to file after match in Kotlin.

관련 문제