[英]IllegalArgumentException while writing on sdcard
我看到這個問題已經解決了很多次,但是奇怪的是我找不到解決方案。
我正在嘗試將二進制文件寫入SD卡。 這是源代碼:
private void saveDataLongs() {
try
{
ObjectOutputStream oos = new ObjectOutputStream(ctx.openFileOutput(Environment.getExternalStorageDirectory().getAbsolutePath()+"/longs.bin", ctx.MODE_WORLD_WRITEABLE));
for (int w=0; w<longCount; w++)
oos.writeLong(longs[w]);
oos.close();
}
catch(IOException e)
{ e.printStackTrace(); }
}
清單包含
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
我收到此錯誤:
01-21 22:19:57.323: E/AndroidRuntime(13713): java.lang.RuntimeException: Unable to start activity ComponentInfo{it.ccc.ccc/it.ccc.ccc.Ccc}: java.lang.IllegalArgumentException: File /sdcard/longs.bin contains a path separator
從其他文章中,我可以理解,某些功能只能在應用程序的專用存儲中編寫,因此它們不希望管理目錄和路徑。 有人可以幫助我嗎? 我會使用其他方法將數據寫入sd,還是只是在執行其他操作之前執行其他操作? 我正在嘗試將一個簡單的二進制文件寫入sdcard(順便說一下,這是一個預先計算的數字序列,我需要將其傳遞到PC上,然后再將其移回資產中,因此,如果有一種不同的獲取方式這個目標,還是可以的)。
非常感謝你。
您說您正在嘗試寫入外部存儲,但是您正在調用openFileOutput()
,它用於內部存儲。
更改:
new ObjectOutputStream(ctx.openFileOutput(Environment.getExternalStorageDirectory().getAbsolutePath()+"/longs.bin", ctx.MODE_WORLD_WRITEABLE));
至:
new ObjectOutputStream(new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "longs.bin")));
或者更好的是:
new ObjectOutputStream(new FileOutputStream(new File(ctx.getExternalFilesDir(null), "longs.bin")));
我喜歡CommonsWare的回答。 我只想補充一點,如果您確實想走一條路,請不要使用/
。 使用File.separator
。 我不認為僅使用/
時就不會出錯。
因此,如果您在sdcard的目錄中創建了一個名為“ To-dos”的子文件夾,則將執行以下操作:
new ObjectOutputStream(new File(Environment.getExternalStorageDirectory() + File.separator + "To-dos", "longs.bin"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.