Java从Resource中读取文本文件

1.设置Resource文件夹

Java是允许开发者将静态资源打到Jar包中,在运行时读取。开发者可以在文件夹“src/main/”下新建一个文件夹"resources",并且在IDE中将这个文件夹设置为资源文件夹,拿IntelliJ Idea为例,在项目设置资源文件夹的过程如图:

设置静态资源文件夹

1).点击项目属性编辑按钮,进入项目属性编辑页;
2).点击Modules编辑子页面;
3).选择对应的项目;
4).选择对应的文件夹;
5).点击Resources按钮。

文件夹设置好了之后,就可以往这个文件夹里面复制项目中需要用到的文件了。

2.读取Resource文件夹中的内容

我们把文本文件保存到Resources以后可以使用ClassLoader来获取Resource文件所在的实际Path:

public class ResourceTest{   
    public static File getResourceFileByStatic(String path){
        String filePath = ResourceTest.class.getClassLoader().getResource(path).getFile();
        File resouce = new File();            
        return resouce;    
    }
}

下面是一段可用的从Resource读取文本文件到字符串的代码供大家参考:

public class ResourceUtil {
    public static String readResource(String path) throws FileNotFoundException{
        Reader reader = null;
        try {
            reader = getResourceReader(path);
            if (reader == null) {
                throw new FileNotFoundException("no file found" + path);
            }
            Scanner s = new Scanner(reader).useDelimiter("\\A");
            return s.hasNext() ? s.next() : "";
        }
        finally {
            if(null != reader){
                try {
                    reader.close();
                }
                catch (IOException ex2){
                    throw new RuntimeException(ex2);
                }
            }
        }

    }

    public static Reader getResourceReader(String name) throws FileNotFoundException{
        InputStream is = null;
        try {
            is = ResourceUtil.class.getClassLoader().getResourceAsStream(getCPResourcePath(name));
            if (is == null) {
                is = new FileInputStream(new File(name));
            }
            return new InputStreamReader(is);
        }
        catch (FileNotFoundException ex){
            if(null != is){
                try {
                    is.close();
                }
                catch (IOException ex2){
                    throw new RuntimeException(ex2);
                }
            }

            throw ex;
        }
    }

    public static String getCPResourcePath(String name) {
        if (!"/".equals(File.separator)) {
            return name.replaceAll(Pattern.quote(File.separator), "/");
        }
        return name;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,881评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,116评论 25 708
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,941评论 6 342
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,200评论 4 61
  • 今儿个过了松散的一天,正好利用这个时间去翻一翻书。 唐艺昕的《愿你喜欢笑,也喜欢自己》,就这本儿了。 写的是她以前...
    白桦i阅读 281评论 0 0