Untitled
unknown
plain_text
a year ago
3.0 kB
30
Indexable
public void generateOutputFile(String entry, String filename) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Android 10+ (API 29+) - Use MediaStore API
saveFileUsingMediaStore(entry, filename);
} else {
// Legacy approach for older versions
saveFileUsingLegacyMethod(entry, filename);
}
}
@RequiresApi(api = Build.VERSION_CODES.Q)
private void saveFileUsingMediaStore(String entry, String filename) {
ContentResolver resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
// Set file details
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
// Insert the file into MediaStore
Uri uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
if (uri != null) {
try (OutputStream outputStream = resolver.openOutputStream(uri)) {
if (outputStream != null) {
outputStream.write(entry.getBytes());
Log.e("File written", "File saved successfully using MediaStore");
}
} catch (IOException e) {
Log.e("File Writing Exception", e.toString());
}
} else {
Log.e("File Creation Error", "Failed to create file entry in MediaStore");
}
}
private void saveFileUsingLegacyMethod(String entry, String filename) {
checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE);
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file = new File(dir, filename);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("File dir", file.getAbsolutePath());
try (FileWriter fileWriter = new FileWriter(file, true)) {
fileWriter.append(entry);
Log.e("File written", file.getAbsolutePath());
} catch (Exception e) {
Log.e("File Writing Exception", e.toString());
}
}
// Alternative: Save to app-specific external storage (doesn't require permissions)
private void saveFileToAppSpecificStorage(String entry, String filename) {
File dir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
if (dir != null) {
File file = new File(dir, filename);
try (FileWriter fileWriter = new FileWriter(file, true)) {
fileWriter.append(entry);
Log.e("File written", file.getAbsolutePath());
} catch (IOException e) {
Log.e("File Writing Exception", e.toString());
}
}
}
}Editor is loading...
Leave a Comment