android intent 获取文件名,Android从onActivityResult获取文件名和路径

我试图实现的目标。我有一个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;

}

请你们可以查看我的代码,并帮助我得到这个工作。任何帮助,将不胜感激。

2015-11-02

Owen Nel

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值