java—在scala play项目中使用GoogleDrive API

c3frrgcw  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(466)

我一直在尝试调整java快速入门指南,以便与scala play项目的google drive api交互,但是我在读取凭证文件时遇到了问题,它说它不存在,但是我尝试了:
绝对路径
来自内容根的路径
源根路径
但这些都不管用。
这是我的项目结构:proj结构
这里是错误:错误
下面是我用来读取文件的代码:

import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver
import com.google.api.client.googleapis.auth.oauth2.{GoogleAuthorizationCodeFlow, GoogleClientSecrets}
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.json.JsonFactory
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.client.util.store.FileDataStoreFactory
import com.google.api.services.sheets.v4.SheetsScopes

import java.io.{File, FileNotFoundException, IOException, InputStreamReader}
import java.security.GeneralSecurityException
import java.util
import java.util.Collections

class GoogleService {
 private val applicationName: String = "Google Sheets API Java Quickstart"
 private val jsonFactory: JsonFactory = JacksonFactory.getDefaultInstance()
 private val tokenDirectoryPath: String = "tokens"

 private val scopes: util.List[String] = Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY)
 private val credentialsFilePath: String = "app/assets/credentials.json"

 @throws[IOException]
 private def getCredentials(HTTP_TRANSPORT: NetHttpTransport) = { // Load client secrets.
   val in = classOf[GoogleService].getResourceAsStream(credentialsFilePath)
   if (in == null) {
     System.out.printf(credentialsFilePath)
     throw new FileNotFoundException(s"Resource not found: $credentialsFilePath")
   }
   val clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(in))
   // Build flow and trigger user authorization request.
   val flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, jsonFactory, clientSecrets, scopes).setDataStoreFactory(new FileDataStoreFactory(new File(tokenDirectoryPath))).setAccessType("offline").build
   val receiver = new LocalServerReceiver.Builder().setPort(8888).build
   new AuthorizationCodeInstalledApp(flow, receiver).authorize("user")
 }

 @throws[IOException]
 @throws[GeneralSecurityException]
 def main(args: String*
         ) {
   val httpTransport = GoogleNetHttpTransport.newTrustedTransport
   getCredentials(httpTransport)
 }
}
iyfjxgzm

iyfjxgzm1#

尝试替换:

val in = classOf[GoogleService].getResourceAsStream(credentialsFilePath)

使用:

val in = getClass.getResourceAsStream(credentialsFilePath)

请注意,资源通常位于 conf 文件夹,这是查找它们的地方。请尝试重新定位文件夹 assetsapp 文件夹到 conf . 然后升级:

private val credentialsFilePath: String = "assets/credentials.json"

相关问题