java项目获取文件路径的几种方式

java web项目中 获取resource路径下的文件路径:

public GetResource{

  String path = GetResource.class.getClassLoader().getResource("xx/xx.txt").getPath();

}

说明:GetResource是当前的类;


SpringBoot读取JSON文件并转化为JSON对象: 

1.通过注解读取文件:

@Value("classpath:static/json/addTask.json")
Resource addTaskJson;

其他配置:

前缀例子说明
classpath:classpath:com/myapp/config.xml从classpath中加载
file:file:/data/config.xml作为 URL 从文件系统中加载
http:http://myserver/logo.png作为 URL 加载
(none)/data/config.xml根据 ApplicationContext 进行判断

2.转化为 字符串 转化为 JSON 对象:

String jsonStr = new String(IOUtils.readFully(addTaskJson.getInputStream(), -1,true));
JSONObject json = JSONObject.parseObject(jsonStr);

注意: 该方法需要 jdk1.8的环境 


springboot 读取外部json文件配置类:

我们在运行一个系统时,不可避免的要加载一些常用的数据,如默认用户,各种数据枚举等。
现在流行的方式为配置一个json文件,此json文件可以放在外部系统读取,也可以放入src/main/resources下,读取的顺序可以和 application.yml 文件一样。加载优先级:外部同级目录 > 外部config目录 > 内部 resources下同级目录 > 内部 resources下config目录。
其实是一段函数控制的:

private static File getResFile(String filename) throws FileNotFoundException {
        File file = new File(filename);
        if (!file.exists()) { // 如果同级目录没有,则去config下面找
            log.debug("不在同级目录,进入config目录查找");
            file = new File("config/"+filename);
        }
        Resource resource = new FileSystemResource(file);
        if (!resource.exists()) { //config目录下还是找不到,那就直接用classpath下的
            log.debug("不在config目录,进入classpath目录查找");
           file = ResourceUtils.getFile("classpath:"+filename);
        }
        return file;
    }

那么具体的实现json文件的解析类,就是:外部依赖

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.51</version>
        </dependency>

JSONHelper.java

@Slf4j
public class JSONHelper {


   /* public static void main(String[] args) {
//        String s =ResolveJsonFileToString("node.json");
//        System.out.println("sss="+s);

//        Map map = (Map) ResolveJsonFileToObject("node.json");
//        System.out.println("map="+map.get("res"));
    }
*/


   /**
   *  将文件流转为json对象,文件存放路径与配置文件路径规范一致
   * @param
   * @return
   * @throws
   */
    public static Object ResolveJsonFileToObject(String filename){
        String str= ResolveJsonFileToString(filename);
        JSONObject jo = JSONObject.parseObject(str);
        return jo;
    }


    /**
    *  通过文件名获取获取json格式字符串,
    * @param filename 文件存放路径与配置文件路径规范一致
    * @return ResolveJsonFileToString
    * @throws
    */
    public static String ResolveJsonFileToString(String filename){

        BufferedReader br = null;
        String result = null;
        try {

//            br = new BufferedReader(new InputStreamReader(getInputStream(path)));
            br = new BufferedReader(new InputStreamReader(getResFileStream(filename),"UTF-8"));
            StringBuffer message=new StringBuffer();
            String line = null;
            while((line = br.readLine()) != null) {
                message.append(line);
            }
            if (br != null) {
                br.close();
            }
            String defaultString=message.toString();
            result=defaultString.replace("\r\n", "").replaceAll(" +", "");
            log.info("result={}",result);

        } catch (IOException e) {
            try {
                ClassLoader classloader = Thread.currentThread().getContextClassLoader();
                InputStream in = classloader.getResourceAsStream(filename);
                br = new BufferedReader(new InputStreamReader(in,"UTF-8"));
                StringBuffer message=new StringBuffer();
                String line = null;
                while((line = br.readLine()) != null) {
                    message.append(line);
                }
                if (br != null) {
                    br.close();
                }
                if (in != null){
                    in.close();
                }
                String defaultString=message.toString();
                result=defaultString.replace("\r\n", "").replaceAll(" +", "");
                log.debug("for jar result={}",result);
            }catch (Exception e1){
                e1.printStackTrace();
            }

        }

        return result;
    }



    private static File getResFile(String filename) throws FileNotFoundException {
        File file = new File(filename);
        if (!file.exists()) { // 如果同级目录没有,则去config下面找
            log.debug("不在同级目录,进入config目录查找");
            file = new File("config/"+filename);
        }
        Resource resource = new FileSystemResource(file);
        if (!resource.exists()) { //config目录下还是找不到,那就直接用classpath下的
            log.debug("不在config目录,进入classpath目录查找");
           file = ResourceUtils.getFile("classpath:"+filename);
        }
        return file;
    }

    /**
    *  通过文件名获取classpath路径下的文件流
    * @param
    * @return
    * @throws
    */
    private static FileInputStream getResFileStream(String filename) throws FileNotFoundException {
        FileInputStream fin = null;
        File file = getResFile(filename);
        log.info("getResFile path={}",file);
        fin = new FileInputStream(file);
        return fin;
    }

}

 


Spring Boot上传文件设置绝对路径和访问绝对路径下的静态资源:

1、设置绝对路径:

在spring boot项目打成jar包后,上传文件的路径会有问题,或者可以成功上传但是服务器上找不到上传成功的文件。这时候我们需要为上传文件设置绝对路径。

application.properties的配置:

#静态资源对外暴露的访问路径
file.staticAccessPath=/api/file/**
#文件上传目录(注意Linux和Windows上的目录结构不同)
#file.uploadFolder=/root/uploadFiles/
file.uploadFolder=d://uploadFiles/

配置上传文件的目录,也可以在这里设置上传文件的大小:
 

@Configuration
public class UploadFileConfig {

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setLocation(uploadFolder);
        //文件最大
        factory.setMaxFileSize("5MB");
        // 设置总上传数据总大小
        factory.setMaxRequestSize("10MB");
        return factory.createMultipartConfig();
    }
}

2、设置虚拟路径,访问绝对路径下资源:

@Configuration
public class UploadFilePathConfig extends WebMvcConfigurerAdapter {

    @Value("${file.staticAccessPath}")
    private String staticAccessPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);
    }
}

这时就可以通过访问 http://localhost:9090/api/file/xxx.txt访问d://uploadFiles/下的资源。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值