[英]Keep getting FileNotFound Exception when trying to open an excel file in Android
我在MainActivity.java中有以下代碼行:
Workbook myWorkBook = WorkbookFactory.create(new File("C://sampleWB.xlsx"));
它將引發以下錯誤:java.io.FileNotFoundException
我也嘗試將excel文件添加到資產文件夾(應用程序> src>主>資產)中,並嘗試了以下代碼,但是拋出了相同的異常。
Workbook myWorkBook = WorkbookFactory.create(new File("sampleWB.xlsx"));
我在AndroidManifest.xml中添加了以下內容,但它也無法解決任何問題:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
如果有幫助,這是我的build.gradle文件:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.test.testProj"
minSdkVersion 26
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation "org.apache.poi:poi:3.17"
implementation "org.apache.poi:poi-ooxml:3.17"
implementation 'com.fasterxml:aalto-xml:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
似乎您使用的是"C://sampleWB.xlsx"
作為文件名。 如此答案中所述 :
和/
不是文件名的有效字符。
要訪問assets
文件夾中的文件,請參考以下答案 :
將您的文本文件放在Android項目下的/ assets目錄中,並按以下方式使用AssetManager類進行訪問。
AssetManager am = context.getAssets();
InputStream is = am.open("default_book.txt");
或者,您也可以將該文件放在/ res / raw目錄中,可以通過該目錄通過id進行訪問,如下所示
InputStream is =
context.getResources().openRawResource(R.raw.default_book);
首先,您需要使用以下命令在運行時請求存儲讀取權限才能讀取文件
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
READ_PERMISSION_REQUEST_CODE);
您可以參考此以獲取更多信息-https: //developer.android.com/training/permissions/requesting
然后,如果您要訪問資產文件夾中的文件-
AssetManager assetManager = getAssets();
assetManager.open("fileName");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.