我正在尝试在外部SD卡(非设备存储)和连接的USB主机(Pendrive)中写入CSV文件。平板电脑操作系统是Kitkat(API级别:17),并有USB端口连接任何USB驱动器,如Pendrive。
我的目的是从我的应用程序中导出Pendrive中的CSV文件。另外,我想在外部SD卡中导出CSV。我试过了official Android documentation here.中显示的文档示例
我发现在Kitkat中,我们不能在外部SD卡中创建多个目录,即所谓的应用程序私有目录(extSdCard/Android/data/packagename/
)。我可以创建此目录,但文件正导出到deviceStorage/Android/data/packagename/
。
如果我在平板电脑的USB端口插入一个pendrive,我可以使用File explorer查看这些文件。因此,我认为也可以在连接的pendrive中导出CSV文件。这是我试图在外部SD卡中导出文件的代码。此代码在外部SD卡中创建一个目录,但该文件在设备存储中创建。
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView logTv, resultTv;
public boolean createCsv(Context context) {
boolean createFlag = false;
if(isExternalStorageWritable() == true) {
try {
String csvFilename = "test.csv";
File csvFile = new File(getExternalFilesDir(null), csvFilename);
FileWriter fw = new FileWriter(csvFile);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("ID,");
bw.write("TEMPARATURE,");
bw.write("DATE,");
bw.write("TIME");
bw.newLine();
bw.flush();
bw.close();
fw.close();
createFlag = true;
} catch (Exception e) {
}
}
return createFlag;
}
void createExternalStoragePrivateFile() {
// Create a path where we will place our private file on external
// storage.
String filename = "sample.txt";
File file = new File(getExternalFilesDir(null), filename);
try {
OutputStream os = new FileOutputStream(file);
String data = "This is sample data.";
os.write(data.getBytes());
os.close();
} catch (IOException e) {
Log.w("ExternalStorage", "Error writing " + file, e);
} catch (Exception e) {
e.printStackTrace();
}
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logTv = (TextView) findViewById(R.id.logTV);
resultTv = (TextView) findViewById(R.id.resultTV);
createExternalStoragePrivateFile();
boolean createCsvFlag = createCsv(getApplicationContext());
}
}
N.B。:我在Manifest文件中添加了<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
。
编辑:
file.getAbsolutePath()
返回/storage/emulated/0/Android/data/packagename/files/sample.txt
,csvFile.getAbsolutePath()
返回/storage/emulated/0/Android/data/packagename/files/test.csv