2022年12月18日

Android 文件寫入

 



package com.tdim.qas;

import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;

public class Document_write {

public static void write_file_to_document(Context context,String file_name, String str){


if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
write_file(context,file_name,str);
}else{
old_write(file_name,str);
}


}

private static void write_file(Context context,String file_name,String str){

try {
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME,file_name); //file name
values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain"); //file extension, will automatically add to file
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS);
Uri uri = context.getContentResolver().insert(MediaStore.Files.getContentUri("external"), values); //important!
OutputStream outputStream = context.getContentResolver().openOutputStream(uri);
outputStream.write(str.getBytes());
outputStream.close();
}catch (Exception e){


}


}

//可能需要權限
private static void old_write(String file_name,String str){

File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File file = new File(dir, file_name);
//Write to file
try {
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(str);
fileWriter.close();

} catch (IOException e) {
//Handle exception
}

}
}

沒有留言:

張貼留言