CodeGym /행동 /Kotlin SELF /Atomic write: temp file + renameToreul tonghan bubun jeo...

Atomic write: temp file + renameToreul tonghan bubun jeojang bangji

Kotlin SELF
레벨 45, 레슨 3
사용 가능

1. wae writeText()ga gakkeum wiheomhan-ga

Filee deiteoreul jeojanghagi sijakhals ttaeneun, munjega yeongwonhi haegyeoldoen geotcheoreom boimnida: “file.writeText(text)reul bulreosseunikka — geureom file i sseoyeojin geojanha.” Hajiman file systemeun hana ui 함수ga anira, jag-eun segyecheoreom jasinmanui gyuchik i inneun byeoldo ui segyeimnida. Geurigo geu segyenun gakkeum yebulchi mothan ildeureul mandeumnida: gajagi peuroseoseu jongryo, yebin gonggan bujok, jeonwon chadan, “saenggak jom”haneun antivirus, ttoneun nugu jega usb reul ppajige haetdeonji (ne, jeongmal geureon il i ireonanida).

Munje nuneun writeText()ga “nappeun” geos i anira, target fileeul jikjeop deopeosseuneun jaejeojangi fileeul junggan sangtaero namgyeo dul su itdaneun jeomimnida. Yereul deureo app i deiteoreul data/expenses.txte jeojanghae dusseul ttae, sae beojeoneul sseugi sijakhaetneunde — sseugi junggan-e modeun geot i kkeun-gyeobeoryeosseumyeon eotteokhaeyo? Geureom file i bin geoscheoreom doego, ttoneun bubunman sseoyeojin chaero namaul su itsseumnida. Geurigo gajang jitkkeumhan geos: daeum silhaeng ttae geugeol ilg-eoryeo haneunde, geu an-e “munjangui ban” heunjeokman nam-a isseul su itdaneun geotimnida.

Sang-sanghae boseyo. Dangsinui fileeun sugje jang-eul jeokneun note imnida. Jikjeop deopeosseugi neun yejeon dap an-eul 지우개로 jiuneun jung-e gabjagi eolgul-eul note-e daemyeo jamdeureobeorineun geotgwa gatseumnida. Achim-e ireonan dangsineun yeongwonhi yejeon haedapdo, saeroun haedapdo eopseumnida. Atomic write jeobgeun-eun saeroun sugjereul chobon-e jeokgo, geu daeum wanseongdoen jongireul note-e gakkeumhi buchineun geotimnida.

Jageun demo: “uriga botong eotteoke sseuneunji” (wa wae jangae ttae wiheomhanji):

import java.io.File

fun main() {
    val target = File("data/expenses.txt")
    target.writeText("...novye dannye...\n")
    println("Sokhranili!") // Sokhranili!
}

Code gwanchomeseoneun modeun geos i ggaekkeuthaego areumdap습니다. Hajiman hyeonsileseoneun sseugi sijakgwa kkeut sai-e manh-eun il i saeng-gil su itsseumnida.

2. atomic write aidee: temp → rename

Jigeum-buteo “bubun jeojang” wiheomeul juligi wihae aepsdeul-i aju jaju sayonghaneun dan-sunhan peurotokeoreul salpyeobogetseumnida. Jeo-nun ilbu러러 pyeonhani seolmyeonghagesseumnida. Wae냐hamyeon “modeun OS wa 모든 file system eseo modeun sanghwang-e서 yeongwonhi 엄밀han atomariseong”eun deo gippeugo eoryeoun 주제imnida. I 과정eseo-neun, majik eopsi, jeo sujun detail-e ppajiji 않고도 siljeoneseo hwolgwa-i nopi go, hwaksilhi deo anjeonhan jeobgeun-eul ik-hineun geos i mokpyomnida.

Aidee neun i렇습니다: saeroun beojeon-i wanseongdoegi jeonkkaji target fileeul 건드리지 않는다. Meonjeon cheonje cheonjeonhi jeonche 텍스트reul imsi file (temp)e target 옆e sseumnida. Temp sseugi ga seonggonghamyeon, geuttae gyeolgwareul “gonggae”hamnida: temp reul target-euro ireum-eul bakkumnida. Temp sseugi 도중 mwonga kkeumkyeobeorimyeon — target fileeun yejeon beojeon daero nam-a, 온전hago ilgil su inneun sangtaeroreul 유지hamnida.

Gwa정 (mini algorithm) seukema:

flowchart TD
    A[Seoburi saeroun 텍스트] --> B[Target 옆e temp filee jeojang]
    B -->|seonggong| C[Gonggae: rename temp -> target]
    B -->|oreu| D[Target eun yejeon daero yujiham]
    C --> E[Nam-a itneun temp jangeul sakje (nam-ass다면)]
    D --> E

Yeogi-seo haeksim-eun “saeroun gyeolgwareul dareun goteseo mandeulgo, geu daeum ppalli gyoche”입니다. Ppalli —ga jungyohan 이유n, “wiheom guyeok”e itneun sigan-i jjaleul surok junggan sangtae-reul eokjeokhi mandeul hwakryul-i 줄어deulgi ttaemun입니다.

3. wae temp neun target wa gateun dir e mandeureoya haneun-ga

“Imsi file”reul deureumyeon, yeoreobun-eun “/tmpe sseujijo”, “hyeonjae directory”, “ttaro temp folder”gachi jeokdanghan gosesseo sseugo 싶eojimnida. Gakkeum-eun geuge joheun aidee가 doemyeonseo, i peurotokeoreseoneun han 가지 jungyohan nuance ga itsseumnida: renameTo()ro ireum-eul bakkuneun geot-eun temp ga target gwa gateun directory e itsseul ttae 훨씬 더 예측 가능h게 동작한다.

Chobojareul wihamyeon i geos-eun “wae eodi-e issneunji ga jungyohaji?”gachi bo일 su 있지만, siljeoneseoneun 차이가 큽니다. Temp ga dareun disk/partition/file system e itdamyeon, rename-i “move”ro byeonhal su 있고, move neun ppalli-godo anjeonhal piryo ga eopsseumnida. Aegga-ro geunyeo ne mujogeon seonggonghaji도 않습니다. Geurigo gakkeum-eun geujeo an doego, renameTo()ga chakhage falsereul dollyeojumyeon kkeut입니다.

Jigeum unyeongcheje guso-reul gippeuge 파고들 piryo neun eopseumnida. Siljeon gyuchik han 가지 man gieokhamnida: temp neun target file i isseul folder an-e mandeureora. Geureomyeon renameTo()ga falsereul dollyeojul hwakryul-i 줄고, “gonggae”ga udoehan-daero jina갈 hwakryul-i 커집니다.

Target 옆e temp gyeonglo-reul mandeuneun jageun util:

import java.io.File

fun tempFor(target: File): File {
    val parent = target.parentFile ?: File(".")
    return File(parent, target.name + ".tmp")
}

Ne, .tmp ireum-eun aju dan순hamnida. Siljeon app eseoneun 충돌-eul 피hagi wihae 무작위 suffix reul butineun gyeongu-ga 많jiman, hakseup proyek teureul wihamyeon uri-neun meonjeo ihae hagi swipge sijakhaetseumnida.

4. renameTo()wa gyeolgwa geomsa

Ireum byeongyeong eun “jeoldae seonggonghaneun cheolbyeok 같은 작업”cheoreom deull릴 su 있지만, JVM method File.renameTo(...)eun jungyohan teukjing-i itsseumnida: return type i Booleanimnida. Jeuk, jak-eob-i silpaehal su 있으며, geu silpaega ban드eusi 예외로 deureonaneun geotdo anibnida (sanghwanggwa platform-e 따라 달라집니다). Geuraeseo uri code neun renameTo()reul “geomsa haeya haneun dan-gye”ro chulbalhaeya 합니다.

Yeogi-seo jeongmal swipge tteoreojineun saenggak ohae: “예외 ga eops-eunikka 괜찮겠지.” Anibnida. true/falsereul 확인하고 daecheoreul haeya 합니다.

Jageun “올바른 스타일” 예시:

import java.io.File

fun main() {
    val from = File("data/a.tmp")
    val to = File("data/a.txt")

    val renamed = from.renameTo(to)
    println("renamed=$renamed") // renamed=true (or false)
}

Man약 renamed=false면, geugeon “jageun bulpyeon”i 아니라, “gonggae ga ireunaji an-assda”neun sinhoimnida. Geureonde geu sanghwang-eseo temp fileeul “manil-eul wihayeo” 지워버리면, hyeonjae gajang saeroun deiteo beojeoneul jiweobeoril 수도 있습니다.

5. atomicWriteText gu현: peurotokeol gwa nuance

Jikjeop sseugi vs temp+rename

Jeonche code reul sseugi jeone, du 접근-u 차이를 “느낌”i 아니라 “jangae si yesang doeneun dongjak”uro jeongrihae du-myeon jo습니다.

Sanghwang Target jiljeop deopeosseugi Temp → rename
Sseugi jung 오류 (gonggan bujok, process sa망) target i bubunman sseoyeojin sangtaega doel su 있음 target eun yejeon beojeon-euro nam음
“Gonggae” dan-gye eseo 오류 daebubun imi 늦eum: target i 이미 yeonghyang bad-ass-eul su 있음 gyoche ga an doel su 있지만, temp ga 남아 있음
Diag “wae file i 망가졌지?” — gakkeum eun geunoehan quest eoneu dan-gye eseo munjega saeng-gyeossneunji pa악hagi deo swipda
Gu현 1 줄로 kkkeut code ga jogeum deureo gajiman, 마음-i pyeon하다

I geosi jikjeop sseugireul “geumji”haneun geot-eun 아닙니다. Dan지, ije file i jungyohal ttae sayonghal su inneun 도구ga 생긴 것입니다.

Gibon beojeon hamssu

Jigeum-buteo atomicWriteText hamssueul mandeureo peurotokeoreul 구현haetsseumnida:

  1. target uleul wihan directory ga jonjaehaneunji 확인 (eop으면 생성)
  2. saeroun 텍스트reul temp e sseugi
  3. target i imi jonjaehamyeon eotteoke halji gyeoljeong (i gangui-eseoneun dan순 jeongchaek: rename-e banghae doejimyeon target sakje)
  4. renameTo(temp -> target)reul 수행hago 결과 확인
  5. eotteon gyeongu-eseodo finallyeseo temp reul 치우gi (best effort)

Yeogi-seo haeksim-eun finallyimnida. I geos-eun seonggonghadeun, silpaehadeun 실행됩니다. Kotlin (geurigo JVM) eun tryreul 빠져나갈 ttae finallyga 실행doem-eul 보janghamnida (muyohan ye외 sanghwang-eun yes외). Geuraeseo cleanup-e ttae jinhwa han 도구입니다.

Cheot beojeon-eun “gajeonghan chaegim” e eopgo, gajang ihae hagi swipdorok sseogetseumnida:

import java.io.File
import java.io.IOException

fun atomicWriteText(target: File, text: String): Boolean {
    val parent = target.parentFile ?: File(".")
    if (!parent.exists() && !parent.mkdirs()) return false

    val temp = File(parent, target.name + ".tmp")

    return try {
        temp.writeText(text)

        if (target.exists() && !target.delete()) return false

        temp.renameTo(target)
    } catch (e: IOException) {
        false
    } finally {
        if (temp.exists()) temp.delete() // best effort
    }
}

Yeogi-seo han 가지 “simrijeok 포인트”: finallyga “temp sakje 100% 보jang”i aniran geosimnida. delete()yeoksi silpaehal su itsseumnida. Hajiman uri-ga wonhaneun geon “절대적 보jang”i 아니라, ilbanjeok-in 오류 sanghwang-eseo imsi filedeul-eul 가능한 han namgijiji aneun 것imnida.

Gadokseong gaeseon: jageun helper hamssu

Hamssu-ga manh-eun jageun 검사reul ha게 되면, chobojadeul-eun daecheoro du 가지 geukdan-e ppajip니다: hana neun modeun geoseul hana ui keun block-e mos아 sseoseo heun-deul리고, dareun hana neun modeun geoseul micohamssu-ro jjagae-beoryeo heulreoreul ileobeor립니다. Uri-neun jung간 jidae-reul seontaekhamnida: “mal-hae judeuneun” bubun-eul helpers-ro ppae-seo, juyo peurotokeol-i han pyeonui iyagi cheoreom ilk히ge ha겠습니다.

Chamgo-ro, Kotlin eun “ceremony boda expression”eul joahago, trydo expression i doeeo value reul return hal su itsseumnida. I geos-eun jeong상이고 gadokseong-e do um i 됩니다.

Directory junbi-reul ttaro ppaeseo hamssu-ro mandeulmida:

import java.io.File

fun ensureParentDir(target: File): Boolean {
    val parent = target.parentFile ?: File(".")
    if (parent.exists()) return parent.isDirectory
    return parent.mkdirs()
}

Geu ri-go target 옆 temp 생성:

import java.io.File

fun tempFor(target: File): File {
    val parent = target.parentFile ?: File(".")
    return File(parent, target.name + ".tmp")
}

Jigeum-eun juyo peurotokeol-eul jogeum deo gadokseong itge daecheolhal su 있습니다:

import java.io.File
import java.io.IOException

fun atomicWriteText(target: File, text: String): Boolean {
    if (!ensureParentDir(target)) return false

    val temp = tempFor(target)

    return try {
        temp.writeText(text)

        if (target.exists() && !target.delete()) return false

        temp.renameTo(target)
    } catch (e: IOException) {
        false
    } finally {
        if (temp.exists()) temp.delete()
    }
}

Algo리즘-eun gajang gatseumnida. Danji ije-neun saram eoneoro seolmyeonghagi swipge doeeotseumnida.

Rename jeone target sakje: teureideu-op

A마 yeoreobun-eun i jul-eul bwan-jeok i 있을 것입니다:

if (target.exists() && !target.delete()) return false

I geos-eun dan순han jeongchaek입니다: file i imi 있다면, renameToga “jari”reul 차지할 su itdorok targeteul jiub니다. Eoneu platform-eseoneun jonjaehaneun file 위로 rename-i doego, eoneu platform-eseoneun an doegi ttaemun-e, hakseup proyek teureul wihamyeon yed측 가능한 동작-eul wihayeo i jeongchaekeul 택합니다.

Hajiman teureideu-op-i 있습니다. Targeteul jiun daeum renameTo()ga silpaehamyeon, “yejeon file eun eopsgo, saeroun file do gonggae doejiji an-eun” sanghwang-i doel su 있습니다. Uri-neun targeteul temp sseugi seonggong hu-e sakje함으로써 (즉, temp reul seonggongjeok-euro sseun daeum) wiheomeul ilbu 줄입니다. Hajiman geuraedo “yejeon file i jiweojin” window ga nam습니다.

I gangui-eseoneun temp→rename gibon peurotokeol-gwa geomsa discipline-eul hwaksilhi 잡습니다. Yejeon beojeoneul deo gangharyeokhi bohohaeya 한다면, gyo체 jeone ijeon fileeul backup haneun byeoldo mechanism-i pil요합니다. Geu geon dareun 주제이며, i gangui bbeon-uireul neomeo pa고들지 않습니다.

Wae tryneun jom 더 “좁아야” haneun-ga

Tto han 가지 dan골 함정: try an-e modeun geoseul da neohneun geot입니다 — 텍스트 saengseong, format, parsing, log 출력까지. Geureom IOExceptionreul japats다고 생각하지만, silje-ro-neun 오류-wi weon-in-i I/O ga 아닐 su 있고, eoneu jijeomeseo munejyeossneunji 감각-eul ileobeor립니다.

“좁은” try/catch jeongsin-eun i렇습니다: file system-e 접근haneun 코드man 안-e 넣습니다. 그 외 logic-eun 밖-e 둡니다. I style-eun expression(try, if, when)eul gadokseong 있게 유지haneun ilgwan된 권장 사항-gwa도 맞습니다: value reul return hage ha고, “han beon-e modeun geos”uro bu풀리지 않게 하십시오.

Yed: i geoseun 괜찮습니다:

val text = lines.joinToString("\n", postfix = "\n")
val ok = atomicWriteText(out, text)

Hajiman i geoseun jom gomin-i pil요합니다:

try {
    val text = lines.joinToString("\n", postfix = "\n")
    out.writeText(text)
    println("ok")
} catch (e: Exception) {
    println("chto-to poshlo ne tak")
}

Du 번째 beojeon-eun “modeun geos-eul 잡았지만”, uimiwa 정보-reul beor렸습니다.

6. Console app e atomic write jeokyonghagi

Yeje-ga “jin공”e isseojimyeon 안 되니, hakseup app iui practical flow-reul 이어가 보겠습니다: console 지출 tracker. I 시점

1
과제
Kotlin SELF, 레벨 45, 레슨 3
잠금
대상 파일 옆
대상 파일 옆
1
과제
Kotlin SELF, 레벨 45, 레슨 3
잠금
보고서 게시
보고서 게시
1
과제
Kotlin SELF, 레벨 45, 레슨 3
잠금
디렉터리 준비
디렉터리 준비
1
과제
Kotlin SELF, 레벨 45, 레슨 3
잠금
중단 없이 저장하기
중단 없이 저장하기
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION