Java 如何将字符串转换为文件以便在Android中共享?
我有一个android应用程序,它使用Java 如何将字符串转换为文件以便在Android中共享?,java,android,Java,Android,我有一个android应用程序,它使用 final JSONArray jsonArray1 = jsonArray; JSONObject export = jsonArray1.getJSONObject(index); 要获取JSON对象,然后使用共享意图: Intent ShareIntent = new Intent(Intent.ACTION_SEND); ShareIntent.setType("text/plain"); ShareIntent.putExtra(Intent.
final JSONArray jsonArray1 = jsonArray;
JSONObject export = jsonArray1.getJSONObject(index);
要获取JSON对象,然后使用共享意图:
Intent ShareIntent = new Intent(Intent.ACTION_SEND);
ShareIntent.setType("text/plain");
ShareIntent.putExtra(Intent.EXTRA_SUBJECT, "THE SUBJECT");
ShareIntent.putExtra(Intent.EXTRA_TEXT, "THE CONTENT IS " + export);
startActivity(Intent.createChooser(ShareIntent, "Send the object via"));
它工作正常,但是,它以纯文本形式共享JSON对象
我理解它为什么这样做
我如何更改它,使JSON对象作为文件共享,最好是一个JSON文件
,例如附加到电子邮件
提前感谢将以下权限添加到您的清单中
. 因此,您需要使用文件提供程序来实现这一点,正如他们的。Ok cool的可能副本中所述,但当我将其放入时,共享意图并不符合startApologies。我忘记了外部应用有时不允许写入外部存储。我对答案进行了编辑,以反映我所做的尝试,我发现它是有效的。您可以使用我提供的代码进行测试。
StringBuilder stringBuilder = new StringBuilder();
File tempFolder = new File(MainActivity.this.getFilesDir(), "temp");
if (!tempFolder.exists()) {
tempFolder.mkdir();
}
JSONObject export = new JSONObject();
try {
export.put("name", "my-name");
export.put("age", "20");
} catch (JSONException e) {
e.printStackTrace();
}
File file = null;
try {
Writer wrt = null;
file = new File(tempFolder, "myJsonFile.json");
wrt = new BufferedWriter(new FileWriter(file));
wrt.write(export.toString());
wrt.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("file/text/plain");
Uri fileUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider",
file);
shareIntent.putExtra(Intent.EXTRA_TEXT, "THE CONTENT IS " + export.toString());
shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Send the object via"));
try {
File f = new File(MainActivity.this.getFilesDir() + "/temp/myJsonFile.json");
InputStream inputStream = new DataInputStream(new FileInputStream(f));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str;
str = bufferedReader.readLine();
stringBuilder.append(str);
tvAccountName.setText(stringBuilder.toString());
} catch (IOException e) {
e.printStackTrace();
}
//then delete the file or you can delete the tempFolder instead;
if(file!=null)file.delete();