Android应用程序-如何写入Android设备的文档文件夹?

ve7v8dk2  于 2023-01-15  发布在  Android
关注(0)|答案(5)|浏览(153)

我想在我的Android应用程序中创建一个XML文件。我想将此文件写入我的Android设备的文档文件夹。稍后我想使用USB将我的Android设备连接到我的PC,并从文档文件夹中读取此XML文件。我的设备是Android Galaxy Tab Pro 10.1,Android 4.4.2。
我已经试过了

String fileName = "example.xml";
String myDirectory = "myDirectory";

String externalStorage = Environment.getExternalStorageDirectory().getAbsolutePath();

File outputFile = new File(externalStorage + File.separator + myDirectory + File.separator + fileName);

但是没有创建任何文件。我还想稍后将该文件从文档文件夹中再次读入May应用程序。
任何帮助都很感激,谢谢!

pxq42qpu

pxq42qpu1#

我知道这有点晚了,但是你可以像这样得到文档目录:

File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File file = new File(dir, "example.txt");

//Write to file
try (FileWriter fileWriter = new FileWriter(file)) {
fileWriter.append("Writing to file!");
} catch (IOException e) {
    //Handle exception
}
zdwk9cvp

zdwk9cvp2#

在Android清单中设置权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

使用此代码写入外部目录

String fileName = "example.xml";
String dirName = "MyDirectory";
String contentToWrite = "Your Content Goes Here";
File myDir = new File("sdcard", dirName);

/*if directory doesn't exist, create it*/
if(!myDir.exists())
    myDir.mkdirs(); 

File myFile = new File(myDir, fileName);

/*Write to file*/
try {
    FileWriter fileWriter = new FileWriter(myFile);
    fileWriter.append(contentToWrite);
    fileWriter.flush();
    fileWriter.close();
}
catch(IOException e){
    e.printStackTrace();
}
x0fgdtte

x0fgdtte3#

在创建文件之前,您必须创建保存文件的目录。请尝试以下操作:- String fileName =“example.xml”;字符串myDirectory =“我的目录”;

String externalStorage = Environment.getExternalStorageDirectory().getAbsolutePath();

File outputDirectory = new File(externalStorage + File.separator + myDirectory );

if(!outputDirectory.exist()){
    outputDirectory.mkDir();
}

File outputFile = new File(externalStorage + File.separator + myDirectory + File.separator + fileName);

outputFile.createFile();
6jygbczu

6jygbczu4#

请尝试重新启动设备,然后检查该文件是否存在。如果存在,则表示您正在创建该文件(看起来应该是基于您的代码创建的),但在设备上扫描媒体之前,该文件不会显示。请尝试实现MediaScannerConnectionClient,使其在创建后显示为可见。

public class MainActivity extends Activity implements MediaScannerConnectionClient {

private MediaScannerConnection msConn;
private File example;

...

@Override
protected void onCreate(Bundle savedInstanceState) {

    ...

    msConn = new MediaScannerConnection(this.getApplicationContext(), this);

    String dir = Environment.getExternalStorageDirectory() + "/Documents/";
    example = new File(dir, "example.xml");

    msConn.connect();

}

@Override
public void onMediaScannerConnected() {
    msConn.scanFile(example.getAbsolutePath(), null);
}

@Override
public void onScanCompleted(String path, Uri uri) {
    msConn.disconnect();
}
7cjasjjr

7cjasjjr5#

从Android 10开始,Android开始使用作用域存储模式来保护用户隐私。如果您想与用户共享此文件,那么您应该将此文件写入Shared Storage。要将文件写入共享存储,必须通过3个步骤完成:-

**第1步:**启动系统选择器以由用户选择目标。这将返回目标目录的URI。

private ActivityResultLauncher<Intent> launcher; // Initialise this object in Activity.onCreate()
private Uri baseDocumentTreeUri;
public void launchBaseDirectoryPicker() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        launcher.launch(intent);
 }

**步骤2:**启动系统选取器以由用户选择目标。这将返回目标目录的URI。此外,您还可以选择保留权限和URI以供将来使用。

@Override
    public void onActivityResult(ActivityResult result) {
        if (result.getResultCode() == Activity.RESULT_OK) {
            baseDocumentTreeUri = Objects.requireNonNull(result.getData()).getData();
            final int takeFlags = (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            // take persistable Uri Permission for future use
            context.getContentResolver().takePersistableUriPermission(result.getData().getData(), takeFlags);
            SharedPreferences preferences = context.getSharedPreferences("com.example.fileutility", Context.MODE_PRIVATE);
            preferences.edit().putString("filestorageuri", result.getData().getData().toString()).apply();
        } else {
            Log.e("FileUtility", "Some Error Occurred : " + result);
        }
}

**步骤3:**将CSV内容写入文件。

public void writeFile(String fileName, String content)  {
        try {
            DocumentFile directory = DocumentFile.fromTreeUri(context, baseDocumentTreeUri);
            DocumentFile file = directory.createFile("text/*", fileName);
            ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(file.getUri(), "w");
            FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor());
            fos.write(content.getBytes());
            fos.close();
        } catch (IOException e) {
            
        }
}

有关详细说明,请阅读“How to Save a file in Shared Storage in Android 10 or Higher“或Android official documentation.

相关问题