Play Framework如何将conf文件夹中的文件作为Java InputStream从本地运行和Web应用程序引用

时间:2017-09-13 18:19:51

标签: java playframework

我有一个应用程序,我需要在Play Framework应用程序中获取文件。我需要引用它以在Java InputStream对象中使用。我需要能够在本地运行应用程序时进行调试,以及在Web应用程序本身中进行引用。

以下是我正在使用的内容:

/** Credentials File Name **/
private static String credentialsFileName = "conf/client_secret.json";

// Load client secrets...
InputStream in = GoogleDrive.class.getResourceAsStream(credentialsFileName);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

但是,当我在本地或在Web应用程序中运行时,它找不到该文件。它会导致NullPointerException。

此文件应放在何处以及如何正确引用?

编辑:

这是更新的课程:

    import javax.inject.Inject;
    import play.Environment;
...
    public class GoogleDrive {

        @Inject
        public static Environment environment;

        /** Credentials File Name **/
        private static String credentialsFileName = "client_secret.json";
    ...

    /**
         * Creates an authorized Credential object.
         * 
         * @return an authorized Credential object.
         * @throws IOException
         */
        @SuppressWarnings("deprecation")
        public static Credential authorize() throws IOException {
            Credential credential = null;
            try {
                // Load client secrets...
                final InputStream in = environment.resourceAsStream(credentialsFileName);
                //InputStream in = GoogleDrive.class.getResourceAsStream(credentialsFileName);
                GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
    ...
            } catch (IOException ex) {
                System.out.println(ex.toString());
                System.out.println("Could not find file " + credentialsFileName);
                ex.printStackTrace();
            }
            return credential;
        }
    ...

    }

1 个答案:

答案 0 :(得分:0)

由于您使用了错误的类加载器,因此无法正常工作。你需要:

@Inject play.Environment,并使用resourceAsStream()方法。在你的情况下:

@Inject
private Environment environment;

final InputStream is = environment.resourceAsStream(credentialsFileName);