Android向Google Drive Appfolder创建JSON文件时遇FileNotFoundException
问题
开发Android应用时,需将数据保存至Google Drive的Appfolder中。已完成Google Cloud Console配置(授权屏幕设置、OAuth客户端ID创建、Drive API启用),并通过AuthorizationClient API完成认证授权。但执行以下代码上传测试JSON文件时出现异常:
// Source: https://developers.google.com/drive/api/guides/appdata private void saveToDriveAppFolder(AuthorizationResult authorizationResult) { GoogleCredentials credentials = GoogleCredentials.create(new AccessToken(authorizationResult.getAccessToken(), null)); // Build a new authorized API client service. Drive service = new Drive.Builder( new NetHttpTransport(), GsonFactory.getDefaultInstance(), new HttpCredentialsAdapter(credentials)) .setApplicationName(getString(R.string.app_name)) .build(); try { // File's metadata. File fileMetadata = new File(); fileMetadata.setName("config.json"); fileMetadata.setParents(Collections.singletonList("appDataFolder")); java.io.File filePath = new java.io.File("files/config.json"); FileContent mediaContent = new FileContent("application/json", filePath); File file = service.files().create(fileMetadata, mediaContent) .setFields("id") .execute(); Log.w(TAG,"File ID: " + file.getId()); } catch (GoogleJsonResponseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
异常信息:
java.io.FileNotFoundException: files/config.json: open failed: ENOENT (No such file or directory)
请问该异常产生的原因是什么?需要检查哪些内容?
原因与排查方向
直接原因
异常核心是代码中指定的本地文件files/config.json不存在。Android应用的文件系统有严格的路径规则,直接使用相对路径files/config.json无法定位到合法的文件位置。
需要检查的内容
- 本地文件路径合法性:Android不支持这种任意相对路径,必须使用系统提供的合法存储目录:
- 应用私有内部存储:通过
getFilesDir()获取根目录,示例:java.io.File filePath = new File(getFilesDir(), "config.json"); - 应用专属外部存储:需先申请对应权限,通过
getExternalFilesDir(null)获取目录。
- 应用私有内部存储:通过
- 目标文件是否已创建:如果是上传已存在的文件,需确保文件已通过
filePath.createNewFile()生成,且已写入内容;如果是新建文件上传,也需先在本地生成文件再传入FileContent。 - 文件访问权限:使用外部存储时,需在Manifest中声明对应权限(Android 13+需
READ_MEDIA_*细粒度权限,低版本需READ_EXTERNAL_STORAGE/WRITE_EXTERNAL_STORAGE),并确保用户已授权。 - 路径拼写准确性:检查目录名大小写、分隔符(Android使用
/)是否正确,避免拼写错误。
修正示例
若要创建新测试JSON文件并上传,可修改路径相关代码:
try { // 保持文件元数据不变 File fileMetadata = new File(); fileMetadata.setName("config.json"); fileMetadata.setParents(Collections.singletonList("appDataFolder")); // 在应用内部存储创建测试文件 java.io.File filePath = new File(getFilesDir(), "config.json"); // 不存在则创建并写入测试内容 if (!filePath.exists()) { filePath.createNewFile(); FileWriter writer = new FileWriter(filePath); writer.write("{\"test_key\": \"test_value\"}"); writer.close(); } FileContent mediaContent = new FileContent("application/json", filePath); File file = service.files().create(fileMetadata, mediaContent) .setFields("id") .execute(); Log.w(TAG,"File ID: " + file.getId()); } catch (Exception e) { e.printStackTrace(); }
内容的提问来源于stack exchange,提问作者OlivierGrenoble
相关产品推荐
相关产品推荐

