[英]Reading a File line by line
我正在創建一個 Android 應用程序來跟蹤財務費用,我希望允許用戶將財務交易批量導入我的應用程序。 交易將以 .csv/.txt 文件的形式出現。
但是,我收到了一個神秘的異常:
java.lang.AbstractMethodError: abstract method "android.content.IContentProvider android.content.ContentResolver.acquireUnstableProvider(android.content.Context, java.lang.String)" at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1780) at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1394) at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1247) at android.content.ContentResolver.openInputStream(ContentResolver.java:967) ....
工作流程如下:用戶選擇要導入的文本文件,App 導入內容。
啟動文件選擇器:
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("*/*");
//intent.addCategory("CATEGORY_OPENABLE");
startActivityForResult(intent, REEQUEST_CODE_IMPORT);
捕捉結果:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REEQUEST_CODE_IMPORT) {
// Make sure the request was successful
Uri path = data.getData();
if (resultCode == RESULT_OK && path != null) {
InputStream inputStream = null;
try {
ContentResolver contentResolver = new ContentResolver(getContext()) {};
// Error happens in the next line
inputStream = contentResolver.openInputStream(path);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(inputStream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = br.readLine()) != null) {
// Do something meaningful...
}
} catch () {
// Catch the exceptions ( I have removed some boiler plate code here...)
} finally {
// Close the path ( I have removed some boiler plate code here...)
inputStream.close();
}
}
}
}
Android 文檔幫我解決了這個問題: Access documents and other files from shared storage - Input Stream
以下代碼改編正在工作:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REEQUEST_CODE_IMPORT) {
// Make sure the request was successful
Uri path = data.getData();
if (resultCode == RESULT_OK && path != null) {
StringBuilder stringBuilder = new StringBuilder();
try (InputStream inputStream = getActivity().getContentResolver().openInputStream(path);
BufferedReader reader = new BufferedReader(
new InputStreamReader(Objects.requireNonNull(inputStream)))) {
String line;
while ((line = reader.readLine()) != null) {
Log.d(TAG, line);
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
String content = stringBuilder.toString();
// Do something with it
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.