先将文件保存在本地然后分享保存的文件
写入文件
public static void writeFile(String FileName,String dirsPath,String content) throws IOException {
File dirs = new File(dirsPath);
File file = new File(dirsPath+ "/" + FileName + ".txt");
//如果文件夹不存在就创建文件夹
if (!dirs.exists()) {
dirs.mkdirs();
}
//如果文件不存在就创建文件
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(content);
fileWriter.close();
}
分享保存的文件
public static void shareFile(Context context, String filePath) {
//实例化File对象
File file = new File(filePath);
//file不为空且文件存在
if (null != file && file.exists()) {
//发送页面
Intent share = new Intent(Intent.ACTION_SEND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//从文件获取内容的URI
Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", file);
share.putExtra(Intent.EXTRA_STREAM, contentUri);
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
}
share.setType("*/*");//此处可发送多种文件
share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(Intent.createChooser(share, "分享文件"));
} else {
Toast.makeText(context, "分享文件不存在", Toast.LENGTH_SHORT).show();
}
}