[英]Getting file path for local Android project files
我想以編程方式訪問將包含在我的項目文件夾中的特定文件。 有沒有辦法做到這一點? 如果是這樣,我的項目文件夾中的位置是否放置文件,以及獲取文件路徑的簡單代碼是什么?
private void saveFileToDrive() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
java.io.File spreadsheet = new java.io.File("Untitled spreadsheet.xlsx");
String filePath = spreadsheet.getAbsolutePath();
System.out.println("file path is"+filePath);
URL fileURL = getClass().getClassLoader().getResource("Untitled spreadsheet.xlsx");
String filePath2 = fileURL.getPath();
System.out.println("file path2 is"+filePath2);
java.io.File fileContent = new java.io.File(filePath);
FileContent mediaContent = new FileContent("application/vnd.ms-excel", fileContent);
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType("application/vnd.ms-excel");
File file = service.files().insert(body, mediaContent).setConvert(true).execute();
if (file != null) {
showToast("File uploaded: " + file.getTitle());
}
else
;
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
將文件放在項目的根文件夾中。 然后獲取文件URL,路徑和其他詳細信息:
File file = new File("test.txt");
String filePath = file.getAbsolutePath();
編輯:替代方式(如果文件在您的類路徑中,例如將文件放在“src”文件夾中,並確保在編譯后將其移動到“bin”或“classes”文件夾中):
URL fileURL = getClass().getClassLoader().getResource(fileName);
String fileName = fileURL.getFile();
String filePath = fileURL.getPath();
這很大程度上取決於您要訪問的文件類型。 您可以將文件放在assets
或res
的相應子目錄中(請參閱/ res和/ assets目錄之間的差異 )。
因此,您希望訪問應用內部的文件; 而你想直接這樣做,也就是說,從Android上下文(然后是[android.|<package_name>.]R.<resource_type>.<resource_name>
)。
您有兩種選擇: res/raw
文件夾或assets/
文件夾( res
父級之外)。
要從https://developer.android.com/guide/topics/resources/providing-resources.html中選擇兩個備注
任意文件以原始形式保存。 要使用原始
InputStream
打開這些資源,請使用資源ID(即R.raw.filename
Resources.openRawResource()
調用Resources.openRawResource()
。但是,如果需要訪問原始文件名和文件層次結構,可以考慮在
assets/
目錄中保存一些資源(而不是res/raw/
)。assets/
中的文件未獲得資源ID,因此您只能使用AssetManager
讀取它們。
要在res/raw/
直接訪問文件,即從Android上下文(然后使用[android.|<package_name>.]R.<resource_type>.<resource_name>
),您可以執行以下操作:
File file = new File("app/src/main/res/raw/country_data_from_world_bank.xml");
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.