我試圖實現的目標。我有一個button
,當按鈕被點擊時,應用程序打開一個文件選擇器,用戶選擇一個文件。該應用程序然後使用FileInputStream
來讀取文件並生成byte[]
。我在button
下面有一個TextView
,然後它將只顯示byte[].length
。下面是在button.onClick()
事件中的代碼:Android從onActivityResult獲取文件名和路徑
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
requestFilePickerCode = parent.registerActivityResultListener(this);
try
{
parent.startActivityForResult(intent, requestFilePickerCode);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(task.getParent(), "Please install a file manager", Toast.LENGTH_SHORT).show();
}
現在這個代碼的工作,我已經證實,它激發onActivityResult
選擇文件時。我簡單地打印Log
顯示data.toString()
產生以下輸出:
11-02 15:14:36.196 2535-2535/? V/class za.co.gpsts.gpsjobcard.utility.handlers.PebbleTypeHandlerBinary: -----> content:/com.android.providers.downloads.documents/document/1
所以似乎越來越選定的文件。當我運行的應用程序,我選擇一個文件,它拋出我的自定義錯誤:
11-02 15:14:36.196 2535-2535/? E/class za.co.gpsts.gpsjobcard.utility.handlers.PebbleTypeHandlerBinary: -----> File does not exist
這顯然表明,我沒有得到的文件。這裏是我的代碼:
@Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data)
{
byte[] fileContent;
// check that data is not null and assign to file if not null
if (data != null)
{
Uri uri = data.getData();
String uriString = uri.toString();
file = new File(uriString);
Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> " + file.toString());
// declare file input stream and read bytes
// write to string variable to test and test output
FileInputStream fin = null;
try
{
fin = new FileInputStream(file);
fileContent = new byte[(int) file.length()];
fin.read(fileContent);
String test = new String(fileContent);
Log.v(PebbleTypeHandlerBinary.class.toString(), "=====> " + test);
}
catch (FileNotFoundException e)
{
Toast.makeText(task.getParent(), "File not found", Toast.LENGTH_SHORT).show();
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> File does not exist");
}
catch (IOException e)
{
Toast.makeText(task.getParent(), "Error reading file", Toast.LENGTH_SHORT).show();
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error while reading the file");
}
finally
{
// close the file input stream to stop mem leaks
try
{
if (fin != null)
{
fin.close();
}
} catch (IOException e)
{
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error closing the stream");
}
}
Log.v(PebbleTypeHandlerBinary.class.toString(), data.toString());
}
return false;
}
請你們可以查看我的代碼,並幫助我得到這個工作。任何幫助,將不勝感激。
謝謝你指點我在正確的方向。我現在已將代碼更改爲'\t \t \t Uri uri = data.getData(); \t \t \t String uriString = uri.getPath(); \t \t \t file = new File(uriString); \t \t \t // String path = file.getAbsolutePath(); \t \t \t Log.v(PebbleTypeHandlerBinary.class.toString(),「----->」+ uriString);'。這仍然會拋出文件未找到... –
我已經設法改變代碼來獲取路徑感謝,但它仍然會拋出文件未找到。堆棧跟蹤現在按以下方式打印路徑:11-02 19:21:57.073 7506-7506 /? V/class za.co.gpsts.gpsjobcard.utility.handlers.PebbleTypeHandlerBinary:----->/document/2 –
你不能簡單地使用uri.getPath()獲取文件路徑 –