为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕田峪7331174 2022-06-15 17:13:07
我有一个程序可以读取多个 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 目录但允许我的用户指定数据的绝对路径(如果他们选择)?
查看完整描述

2 回答

?
守着一只汪

TA贡献1872条经验 获得超4个赞

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();

}


查看完整回答
反对 回复 2022-06-15
?
RISEBY

TA贡献1856条经验 获得超5个赞

这很简单:


        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();

        }

    }


查看完整回答
反对 回复 2022-06-15
  • 2 回答
  • 0 关注
  • 111 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号