CSV全名是Comma Separated Value,
它是一種用逗號作為分隔的檔案類型,
常用於資料庫資料的匯入與匯出,
非常簡單、方便的讓程式讀取,
且因為簡潔,
所以不需要多龐大的系統便能開啟CSV檔進行檔案編輯。
今天要接續昨天的匯入分享,
分享如何將APP內的資料匯出成CSV檔。
建議先看完
[Android Studio菜鳥的學習分享]使用他人製作元件模板
與
[Android Studio菜鳥的學習分享]檔案選擇器應用(上)-匯入CSV檔案
再服用這篇分享~
匯入CSV檔的資料至 csvArrayList 。
為今天我檔案匯入與匯出的變數。
將 csvArrayList 內的資料匯出至指定的資料夾,
檔案名稱為 csvDataList.csv 。
csvArrayList.get(0);
csvArrayList.get(1);
csvArrayList.get(2);
csvArrayList.get(3);
csvArrayList.get(4);
csvArrayList.get(5);
csvArrayList.get(0) -> 1
csvArrayList.get(1) -> apple
csvArrayList.get(2) -> 2
csvArrayList.get(3) -> banana
csvArrayList.get(4) -> 3
csvArrayList.get(5) -> cherry
public class WriteCSVThread extends Thread{
}
ArrayList<String> data;
String fileName = "csvDataList.csv";
String folder;
StringBuilder stringBuilder;
private void createFolder(){
File folderPath = new File(folder);
boolean folderExists = folderPath.exists();
if(!folderExists){
folderPath.mkdir();
}
}
將取得的資料與要匯出至的資料夾放入變數data & folder
public WriteCSVThread(ArrayList<String> data, String folder){
this.data = data;
this.folder = folder;
}
@Override
public void run(){
super.run();
createFolder();
}
File.separator => /
File newFile = new File(folder + File.separator + fileName);
try{
}
catch (Exception error){
error.printStackTrace();
}
FileOutputStream fileOutputStream = new FileOutputStream(newFile,false);
stringBuilder = new StringBuilder();
for (String arrayData:data){
stringBuilder.append(arrayData).append(",");
}
stringBuilder.append("\n");
fileOutputStream.write(stringBuilder.toString().getBytes());
fileOutputStream.flush(); //齊平
fileOutputStream.close();
folderName方便放入資料夾位置
private void saveCsv(String folderName){
}
if(folderName != ""){
}
else {
textOutput.setText("請選擇匯出路徑!!");
}
if(csvDataList.isEmpty()){
textOutput.setText("無資料!!");
}
else {
}
private WriteCSVThread writeCSVThread;
writeCSVThread = new WriteCSVThread(csvDataList,folderName);
writeCSVThread.run();
textOutput.setText("匯出成功!!");
以下介紹請看
[Android Studio菜鳥的學習分享]使用他人製作元件模板
btnFileOutput.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(permissionGranted()) {
DirectoryPickerDialog directoryPickerDialog = new DirectoryPickerDialog(MainActivity.this,
() -> textOutput.setText("Canceled!!"),
files -> saveCsv(files[0].getPath()));
directoryPickerDialog.show();
}
else{
requestPermission();
}
}
});
以下介紹請看
[Android Studio菜鳥的學習分享]使用他人製作元件模板
private boolean permissionGranted(){
return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission(){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}