![](/img/trans.png)
[英]getResourceAsStream() - InputStream null when using relative path
[英]Java InputStream object using getResourceAsStream is null when calling from web application but works when run in Eclipse
我有使用getResourceAsStream
方法創建InputStream
對象的代碼。
當我在Eclipse中運行時,此方法工作正常,但是,當我從Web應用程序調用時,它始終為null-無法找到該文件。
java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at google.GoogleDrive.authorize(GoogleDrive.java:84)
at google.GoogleDrive.getDriveService(GoogleDrive.java:106)
at google.GoogleDrive.uploadFile(GoogleDrive.java:123)
這是完整的課程:
package google;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
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;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpTransport;
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.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import play.Configuration;
import utils.AppGlobals.StringControl;
public class GoogleDrive {
/** Application name. */
private static final String APPLICATION_NAME = "Case Manager";
/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"),
".credentials/googledrivejava");
/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
/** Credentials File Name **/
private static String credentialsFileName = "client_secret.json";
/**
* Global instance of the scopes required by this quickstart.
*
* If modifying these scopes, delete your previously saved credentials at
* ~/.credentials/drive-java-quickstart
*/
// private static final List<String> SCOPES =
// Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
*
* @return an authorized Credential object.
* @throws IOException
*/
public static Credential authorize() throws IOException {
Credential credential = null;
try {
// Load client secrets...
InputStream in = GoogleDrive.class.getResourceAsStream("client_secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
} catch (IOException ex) {
System.out.println(ex.toString());
System.out.println("Could not find file " + credentialsFileName);
ex.printStackTrace();
}
return credential;
}
/**
* Build and return an authorized Drive client service.
*
* @return an authorized Drive client service
* @throws IOException
*/
public static Drive getDriveService() throws IOException {
Credential credential = authorize();
return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
}
public static void main(String[] args) throws IOException {
try {
uploadFile("C:\\WebDev\\license.txt");
} catch (Exception ex) {
System.out.println(ex.toString());
ex.printStackTrace();
}
}
public static String uploadFile(String fullFilePath) throws IOException {
String fileID = "";
try {
// Build a new authorized API client service.
Drive service = getDriveService();
File fileMetadata = new File();
String fileName = StringControl.rightBack(fullFilePath, "\\");
String fileContentType = getContentType(fileName);
fileMetadata.setName(fileName);
// Set the folder...
String folderID = Configuration.root().getString("google.drive.folderid");
fileMetadata.setParents(Collections.singletonList(folderID));
java.io.File filePath = new java.io.File(fullFilePath);
FileContent mediaContent = new FileContent(fileContentType, filePath);
File file = service.files().create(fileMetadata, mediaContent).setFields("id, parents").execute();
fileID = file.getId();
} catch (Exception ex) {
System.out.println(ex.toString());
ex.printStackTrace();
}
return fileID;
}
public static String getContentType(String filePath) throws Exception {
String type = "";
try {
Path path = Paths.get(filePath);
type = Files.probeContentType(path);
System.out.println(type);
} catch (Exception ex) {
System.out.println(ex.toString());
ex.printStackTrace();
}
return type;
}
}
我嘗試了這篇文章中的一些其他選項: 加載字體文件時,Eclipse Java File FileInputStream與Input Stream
但是沒有運氣。 感謝幫助。
確認在編譯Web應用程序時,資源包含在目標目錄中。 您的json -file可能不會與編譯的類一起復制,因此您將得到null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.