zoukankan      html  css  js  c++  java
  • Java获取配置文件跟路径

    一直以为使用new File(相对路径)可以读取class目录下的文件,其实不然。网上查询了一些资料,弄清楚了原理,总结如下:

    package com.coshaho.learn;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    public class FilePathLearn
    {
        public static void main(String[] args) throws IOException
        {
            // 方案1
            // 获取代码工程路径,生产环境上只有class文件,没有java文件与代码工程,这种方式不可取
            File file = new File("");
            System.out.println(file.getCanonicalPath());
            
            // 方案2
            // 获取代码工程路径,生产环境上使用会出现问题
            System.out.println(System.getProperty("user.dir")); 
            
            // 方案3
            // 获取class文件根目录(路径中包含空格会被转义为%20,此时new File会失败)
            file = new File(FilePathLearn.class.getResource("/").getPath());
            System.out.println(file.getCanonicalPath());
            
            // 方案4
            // 获取class文件目录(路径中包含空格会被转义为%20,此时new File会失败)
            file = new File(FilePathLearn.class.getResource("").getPath());
            System.out.println(file.getCanonicalPath());
            
            // 方案5
            // 可以看出来,这种方法的效果和方案3效果相同
            file = new File(FilePathLearn.class.getClassLoader().getResource("").getPath());
            System.out.println(file.getCanonicalFile()); 
            
            // 由于路径可能包含空格,new file可能失败,所以可以直接打开流读取文件
            InputStream stream = FilePathLearn.class.getResource("CE_Excel.xml").openStream();
            InputStreamReader reader = new InputStreamReader(stream);
            BufferedReader bufReader=new BufferedReader(reader); 
            
            String str = null;
            while ((str = bufReader.readLine()) != null)
            {
                System.out.println(str);
            }
        }
    }
  • 相关阅读:
    shiro
    leetcode696 C++ 36ms 计算二进制子串
    leetcode557 C++ 56ms 反转字符串中的每个单词
    leetcode657 C++ 16ms 判断回环
    leetcode709 C++ 4ms 转换成小写字母
    leetcode141 C++ 8ms 环形链表
    leetcode160 C++ 32ms 相交链表
    leetcode234 C++ 28ms 回文链表
    leetcode203 C++ 28ms 删除链表中满足条件的节点
    leetcode83 C++ 12ms 删除有序链表中的重复元素
  • 原文地址:https://www.cnblogs.com/coshaho/p/7466684.html
Copyright © 2011-2022 走看看