gpt4 book ai didi

java - 如何在android中将字符串存储到文件中

转载 作者:行者123 更新时间:2023-12-02 04:51:16 25 4
gpt4 key购买 nike

我正在尝试将字符串存储到应存储在设备上的文件中

我有以下代码将字符串存储到名为exportstring的变量中:

final JSONArray jsonArray1 = jsonArray;
JSONObject export = jsonArray1.getJSONObject(index);
String exportString = export.toString();
writeToFile(exportString);

然后我有一个名为 writeToFile

的函数
private void writeToFile(String content) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/test.txt");

if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file);
writer.append(content);
writer.flush();
writer.close();
} catch (IOException e) {
}
}

当我运行它时,我收到一条消息“文件已保存”

但是当我打开文件管理器时,我在任何地方都看不到它。

文件保存到哪里?

或者我在这里做错了什么?

最佳答案

要将文件存储在“下载”文件夹中,请更改:

File file = new File(Environment.getExternalStorageDirectory() + "/test.txt");

至:

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/test.txt");

更新:尝试保存文件之前,您应该确保拥有所需的权限,在本例中是写入存储的权限。以下是如何执行此操作的简短示例:

protected boolean checkPermission() {
int result1 = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result1 == PackageManager.PERMISSION_GRANTED ) {
return true;
} else {
return false;
}
}

protected void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "Write External Storage permission allows us to do store files. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}
}
}


@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 100:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("permissionCheck", "Permission Granted, do what you want to do when user grants the permission here!!!");

} else {
Log.d("permissionCheck", "Permission Denied, do what you want to do when user denies the permission here...");
}
break;
}
}

将上面的代码包含到您的 Activity (或您当前所在 Activity 之前的任何 Activity )中,并尝试将字符串存储到文件中之前执行以下操作:

if(!checkPermission()){
Log.d("permissionCheck", "Need to get the permissions");
requestPermission();
}else{
Log.d("permissionCheck", "Already have the permissions");
}

查看 logcat 中的日志:

enter image description here

关于java - 如何在android中将字符串存储到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56439833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com