我想在下載檔案夾中為每一天保留一個日志文本檔案。我想在下載檔案夾中我自己的日志檔案夾(MyApp Log檔案夾)中存盤基于日的文本檔案。
當我洗掉My App Log檔案夾時,我無法在同一位置以相同的名稱創建這個檔案夾。同樣地,當我創建的文本檔案被洗掉時,我也不能以相同的文本檔案名創建一個檔案。resolver.insert(downloadUri, contentValues);總是回傳 null。
即使我在查詢是否有屬于該路徑的檔案時得到一個空的結果,我也無法創建相同的檔案。
我創建檔案的函式:
public static void createFile{
String contentType = "text/log"/span>。
Date cDate = new Date(System.currentTimeMillis())。
String today = new SimpleDateFormat("yyy_MM_dd")。 format(cDate)。
long seconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentValues contentValues = new ContentValues()。
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, today ".txt"); /2021_10_13.txt
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, contentType);//text/log。
contentValues.put(MediaStore.MediaColumns.DATE_ADDED, seconds);//System.currentTimeMillis。
contentValues.put(MediaStore.MediaColumns.DATE_MODIFIED, seconds);//System.currentTimeMillis。
contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1) 。
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS File.separator "MyApp Log"); /Download/MyApp Log
ContentResolver resolver = getContext().getContentResolver()。
outputUri = resolver.insert(getDownloadUri(), contentValues)。
if (outputUri == null)
throw new IOException("Failed to create new MediaStore record;)
try (final OutputStream stream = resolver.openOutputStream(outputUri)) {
if (stream == null)
return;
} finally {
ContentValues updateValues = new ContentValues() 。
updateValues.put(MediaStore.MediaColumns.IS_PENDING, 0) 。
resolver.update(outputUri, updateValues, null, null)。
}
}
public static @NonNull
Uri getDownloadUri() {
if (Build.VERSION.SDK_INT < 29) {
return getLegacyUri(Environment.DIRECTORY_DOWNLOADS)。
} else {
return MediaStore. Downloads.EXTERNAL_CONTENT_URI;
}
我正在查詢檔案是否存在的函式:
public static Uri getExternalContentUriFromFile(Uri externalUri, String filePath) {
if (externalUri == null)
return null;
try (Cursor cursor = getContentResolver().query(externalUri, new String[]{MediaStore.MediaColumns._ID}。
MediaStore.MediaColumns.DATA "=? ", new String[]{filePath}, null>) {
if (cursor != null && cursor.moveToFirst() ) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID)) 。
return Uri.withAppendedPath(externalUri, ""/span> id)。
}
return null。
}
uj5u.com熱心網友回復:
我自己找到了一個解決方案:
int fileNo = 0;
Uri uri = saveToUri(fileName, contentType, seconds, relativePath)。
if (uri == null) {
while (fileNo < 4 && uri == null) {
fileNo ;
fileName = AttachmentUtil.removeExtensionForName(fileName) "(" fileNo ")" extension。
uri = saveToUri(fileName, contentType, seconds, storageName File.separator myDirName, storageUri) 。
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/310455.html
標籤:
上一篇:安卓11存盤訪問和Java檔案庫
