새 콘텐츠를 쓰기 전에 파일 지우기 (Java, Android)

Nov 09 2020

다음 코드를 사용하여 새 파일 (이진 또는 JSON)을 만들거나 Android에서 기존 파일을 다시 작성합니다.

ParcelFileDescriptor pfd = this.getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
fileOutputStream.write(bytes);
fileOutputStream.close();
pfd.close();

문제는 파일이 이미 있고 콘텐츠 크기가 더 크면 이전 콘텐츠가 남아 있다는 것입니다. 예를 들어 JSON은 다음과 같을 수 있습니다.

[
    "a",
    "b"
]   "c",
    "d"
]

쓰기 전에 파일을 정리하거나 나머지 내용을 지우려면 어떻게합니까?

답변

3 CommonsWare Nov 09 2020 at 01:33

"wt"대신을 사용하여 w파일에 t쓰기 전에 파일 ( ) 을 잘라 보십시오 .

2 MustafaPoya Nov 09 2020 at 01:33

FileOutputStream파일 내용을 덮어 쓰라는 두 번째 매개 변수로 의 초기화를 변경해야 합니다.

FileOutputStream(pfd.getFileDescriptor(), false);두 번째 매개 변수 는 덮어 쓰는 true동안 추가 false됩니다.

ParcelFileDescriptor pfd = this.getContentResolver().openFileDescriptor(uri, "wt");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
fileOutputStream.write(bytes);
fileOutputStream.close();
pfd.close();
1 El.MENSI Nov 09 2020 at 02:36

파일에 대한 액세스 모드 :

 1. "r" for read-only access,
 2. "w" for write-only access (erasing whatever data is currently in the file),
 3. "wa" for write-only access to append to any existing data, 
 4. "rw" for read and write access on any existing data, 
 5."rwt" for read and write access that truncates any existing file.

rwt를 시도해보십시오.