如何从 Java 中用户提供的输入中定位文件

我有一个程序可以读取多个 json 文件,然后对这些文件中包含的信息进行一些分析。


我的项目结构布局如下:


    /main

        /java

        /resources

            /data

                file1.json

                file2.json

                ...

                fileN.json

如果用户想要分析不同的数据集,我试图让他们能够指定备用位置。


我正在使用以下代码创建一个 File 对象数组:


 ClassLoader loader = myClass.class.getClassLoader();

 URL url = loader.getResource(location);

 try {

     String path = url.getPath();

     return new File(path).listFiles();

} catch (NullPointerException e) {

     throw new FileNotFoundException();

}

注意:我使用 myClass.class.getClassLoader() 因为我是从静态方法而不是从实例化对象调用的。


当location = "data". 但是,如果我将绝对路径传递到location = "/Users/myuser/Desktop/data"其中包含相同数据文件的不同位置(例如:),我将得到一个 NPE。


有没有一种好方法可以让我默认使用 src/main/resources 目录但允许我的用户指定数据的绝对路径(如果他们选择)?


慕田峪7331174
浏览 113回答 2
2回答

守着一只汪

ClassLoader loader = myClass.class.getClassLoader();URL url = loader.getResource(location);上面的代码仅适用于类路径中存在的文件。因此,您可以将其更改为默认从 src/main/resources 目录读取,并通过将其更新为用户给出的绝对路径:try {     return new File(location).listFiles();} catch (NullPointerException e) {     throw new FileNotFoundException();}

RISEBY

这很简单:        ClassLoader cl = myClass.class.getClassLoader();        URL url = cl.getResource(location);        if (url == null) {            //the location does not exist in class path            return new File(location).listFiles();        } else {            return new File(url.getPath()).listFiles();        }但我认为更好的方法是:    private File[] readFile(String userLocation) {        if(userLocation == null || userLocation.isEmpty()) {            // user do not specify the path            return new File(myClass.class.getResource("data").getPath()).listFiles();        } else {            return new File(userLocation).listFiles();        }    }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java