我想要实现的功能是,当用户点击一个按钮时,应用程序会打开一个文件选择器,让用户选择一个文件。然后应用程序使用FileInputStream读取文件并生成一个byte[]。在按钮下方有一个TextView,它将简单地显示byte[]的长度。以下是button.onClick()事件中的代码:
请大家帮我检查一下代码并帮助我让它正常运行起来。非常感谢您的帮助。
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;
}
请大家帮我检查一下代码并帮助我让它正常运行起来。非常感谢您的帮助。
Uri uri = data.getData(); String uriString = uri.getPath(); file = new File(uriString); // String path = file.getAbsolutePath(); Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> " + uriString);
。但是仍然抛出文件未找到的异常... - Owen Nel