Xóa tệp trước khi viết nội dung mới vào đó (Java, Android)

Nov 09 2020

Tôi đang sử dụng mã sau để tạo tệp mới (nhị phân hoặc JSON) hoặc viết lại tệp hiện có trong Android:

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

Vấn đề là khi tệp đã tồn tại và kích thước nội dung của nó lớn hơn, nội dung cũ vẫn còn. Ví dụ: JSON có thể trông giống như

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

Làm cách nào để làm sạch tệp trước khi ghi vào hoặc xóa nội dung còn lại?

Trả lời

3 CommonsWare Nov 09 2020 at 01:33

Hãy thử sử dụng "wt"thay vì w, để cắt ngắn tệp ( t) trước khi ghi vào tệp đó.

2 MustafaPoya Nov 09 2020 at 01:33

bạn nên thay đổi cách khởi tạo FileOutputStreambằng tham số thứ hai có nghĩa là ghi đè lên nội dung tệp:

FileOutputStream(pfd.getFileDescriptor(), false);tham số thứ hai nếu nó truethì nó nối thêm trong khi falsenó sẽ ghi đè.

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

Chế độ truy cập cho tệp:

 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.

Hãy thử xem nó có thể làm được việc