[英]Writing a file to sdcard
我正在嘗試從Http帖子回復到SD卡上的文件寫一個文件。 一切正常,直到檢索到數據的字節數組。
我已經嘗試在清單中設置WRITE_EXTERNAL_STORAGE
權限,並嘗試了我在網上找到的許多不同的教程組合。
我所能找到的只是使用活動的openFileOutput("",MODE_WORLD_READABLE)
方法,但我的應用程序如何使用線程寫入文件。 具體來說,當一個文件必須被寫入時,從另一個線程調用一個線程,所以即使我嘗試了它,給一個活動對象也不起作用。
該應用程序已經走了很長的路,我無法改變應用程序當前的編寫方式。
拜托,有人幫幫我嗎?
代碼 :
File file = new File(bgdmanip.savLocation);
FileOutputStream filecon = null;
filecon = new FileOutputStream(file);
byte[] myByte;
myByte = Base64Coder.decode(seReply);
bos.write(myByte);
filecon.write(myByte);
myvals = x * 11024;
bgdmanip.savLocation
包含整個文件路徑。 seReply
是來自HttpPost
響應的字符串回復。 第二組代碼是參考x
循環的。 文件已創建但仍為0字節。
//------------------------------WRITING DATA TO THE FILE ---------------------------------
btnWriteSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(v.getContext(),"Done writing SD 'mysdfile.txt'", Toast.LENGTH_SHORT).show();
txtData.setText("");
}
catch (Exception e)
{
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
//---------------------------READING DATA FROM THE FILE PLACED IN SDCARD-------------------//
btnReadSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null)
{
aBuffer += aDataRow ;
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(v.getContext(),"Done reading SD 'mysdfile.txt'",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
與此同時在Android.Manifest中寫下此權限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
openFileOutput()
方法將數據寫入應用程序的私有數據區(而不是SD卡),因此可能不是您想要的。 您應該能夠調用Environment.getExternalStorageDirectory()
來獲取SD卡的根路徑並使用它創建FileOutputStream
。 從那里,只需使用標准的java.io例程。
這是一個示例:
// Log used as debug
File log = new File(Environment.getExternalStorageDirectory(), "Log.txt");
try {
out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), false));
out.write(new Date().toString());
out.write(" : \n");
} catch (Exception e) {
Log.e(TAG, "Error opening Log.", e);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.