Android文字圖片寫入CSV(Base64)并分享
做的一個分享的功能,將文字圖片以CSV的形式分享到郵件之類的應用。
首先,CSV逗號分隔值文件格式(Comma-Separated Values),純文本形式,逗號分隔,一行數據不跨行。
圖片轉換成Base64字符串
public String writeBase64(String path) { //path圖片路徑
byte[] data = null;
try {
InputStream in = new FileInputStream(path);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Base64.encodeToString(data, Base64.NO_WRAP); //注意這里是Base64.NO_WRAP
}最后返回 Base64.encodeToString(data, Base64.NO_WRAP), 注意 這里要使用Base64.NO_WRAP,而不是Base64.DEFAULT。default當字符串過長(RFC2045里規定了每行最多76個字符換行),自動會加入換行符,影響使用,用NO_WRAP解決。
生成和寫入CSV
public File writeCsv() {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/csv/"; //CSV文件路徑
File csv = new File(path + "KnowYourTeam.csv");
File pa = new File(path);
if (!pa.exists()) {
pa.mkdirs();
}
if (!csv.exists()) {
try {
csv.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
csv.delete(); //這里寫的如果文件存在會刪除文件新建一個文件
csv.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(csv, true));
ArrayList<Person> list = new PersonDao(this).queryAll(); //數據庫取Person List
for (Person person : list) { //循環寫入person數據(name,title,image)
String img = writeBase64(person.getPicPath()); //getPicPath()路徑
bw.write(person.getName() + "," + person.getTitle() + "," + img);
bw.newLine(); //換行,一行一組數據
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
return csv;
}最后分享
File csv = writeCsv();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(csv));
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "KnowYourTeam shared data");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設置日期格式
sendIntent.putExtra(Intent.EXTRA_TEXT, "There is CSV. " + df.format(new Date()));
sendIntent.setType("text/comma-separated-values");
startActivity(Intent.createChooser(sendIntent, "share"));Intent.ACTION_SEND 帶附件發送
Intent.createChooser(sentIntent, "share") 可以選擇支持這種格式的應用打開分享
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!