java - 使用 YOUTUBE-API 的视频路径字符串

标签 java nullpointerexception youtube youtube-api filepath

我正在使用 youtube-api,当我设置时,视频上传示例工作正常 video_path 字符串到放置在工作区下的“/video_name.mp4”。

private static String video_path = "/video_name.MP4";

但是一旦我将其设置为绝对路径 private static String video_path = "C:/Users/Ip300/Desktop/video_name.MP4";

我收到错误

" Throwable: null java.lang.NullPointerException..."

就像视频不存在一样。 PS:我在 Windows 上测试了它正确重定向到视频的路径。

完整代码是:

public class UploadVideo {

private static YouTube youtube;
private static final String VIDEO_FILE_FORMAT = "video/*";
private static final String SAMPLE_VIDEO_FILENAME = "video_name.mp4";
private static  String video_path = "C:/Users/Ip300/Desktop/video_name.MP4";

public static void main(String[] args) {

    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload");
    try {     
        Credential credential = Auth.authorize(scopes, "uploadvideo");
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName(
                "youtube-cmdline-uploadvideo-sample").build();
        System.out.println("Uploading: " + SAMPLE_VIDEO_FILENAME);
        Video videoObjectDefiningMetadata = new Video();
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status); 
        VideoSnippet snippet = new VideoSnippet();           
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("Test Upload via Java on " + cal.getTime());
        snippet.setDescription(
                "Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());
        // Set the keyword tags that you want to associate with the video.
        List<String> tags = new ArrayList<String>();
        tags.add("test");
        tags.add("example");
        tags.add("java");
        tags.add("YouTube Data API V3");
        tags.add("erase me");
        snippet.setTags(tags);
        videoObjectDefiningMetadata.setSnippet(snippet);
        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT,
                UploadVideo.class.getResourceAsStream(video_path));
        YouTube.Videos.Insert videoInsert = youtube.videos()
                .insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
        uploader.setDirectUploadEnabled(false);
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch (uploader.getUploadState()) {
                    case INITIATION_STARTED:
                        System.out.println("Initiation Started");
                        break;
                    case INITIATION_COMPLETE:
                        System.out.println("Initiation Completed");
                        break;
                    case MEDIA_IN_PROGRESS:
                        System.out.println("Upload in progress");
                        System.out.println("Upload percentage: " + uploader.getProgress());
                        break;
                    case MEDIA_COMPLETE:
                        System.out.println("Upload Completed!");
                        break;
                    case NOT_STARTED:
                        System.out.println("Upload Not Started!");
                        break;
                }
            }
        };
        uploader.setProgressListener(progressListener);
        System.out.println("\n================== Returned Video ==================\n");
        System.out.println("  - Id: " + returnedVideo.getId());
        System.out.println("  - Title: " + returnedVideo.getSnippet().getTitle());
        System.out.println("  - Tags: " + returnedVideo.getSnippet().getTags());
        System.out.println("  - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus());
        System.out.println("  - Video Count: " + returnedVideo.getStatistics().getViewCount());
    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}
}

最佳答案

Class.getResourceAsStream() 需要一个前导“/”,以便将路径解释为绝对路径。如果没有它,路径应该是相对路径。 而 ClassLoader.getResourceAsStream() 仅使用绝对路径,因此不需要前导“/”。

如果找不到资源,两者都会返回null

您可以使用 UploadVideo.class.getResourceAsStream() 方法来初始化 YouTube.Videos.Insert videoInsert

欲了解更多信息: http://www.javaworld.com/article/2077352/java-se/smartly-load-your-properties.html

Note: If you use a native path and work on a Windows machine, the proper file seperator is ' \ ' instead of ' / '.

However for native paths ( e.g. c:\path\file ) there is no need for getResourceAsStream(). You can simply use new FileInputStream("c:\path\file");

关于java - 使用 YOUTUBE-API 的视频路径字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43239485/

相关文章:

java - 如何在 Webview 中单击屏幕上隐藏和显示 Android 组件?

java - java JRE tarball 和 EXE 有什么区别

java - 使用LWJGL和Slick-Util加载声音

java - Android App 中的 NullPointerException

java swing 单选按钮 - java.lang.NullPointerException

wordpress - 如果用户的登录页面仅显示视频-YouTube

java - Toplink 对象未显示在 JDeveloper 中的 Toplink Map 节点下

java - 如何在java中获取字符串的特定部分?

python - 如何使我的Discord机器人播放YouTube上的音频

php - Google Youtube API 插入评论总是返回错误响应 403 - "Insufficient Permission"- 域 "global"