Java项目CSV文件通用路径配置问题求助
解决Java跨环境读取CSV文件路径问题
方法1:基于项目根目录的相对路径(推荐)
利用System.getProperty("user.dir")获取当前项目根目录,结合Paths.get()自动适配不同系统的路径分隔符,拼接文件路径:
public static ArrayList<String[]> loopCSV() throws DBAppException { try { String line; // 获取项目根目录 String projectRoot = System.getProperty("user.dir"); // 自动适配系统路径分隔符,拼接目标文件路径 String csvPath = Paths.get(projectRoot, "Metadata", "Metadata.csv").toString(); // 使用try-with-resources自动关闭流,避免资源泄漏 try (BufferedReader br = new BufferedReader(new FileReader(csvPath))) { ArrayList<String[]> TablesName = new ArrayList<>(); while ((line = br.readLine()) != null) { String[] r = line.split(","); TablesName.add(r); } return TablesName; } } catch (Exception e) { throw new DBAppException("can not read the csv file: " + e.getMessage()); } }
方法2:读取资源目录下的文件(适合打包Jar场景)
如果是Maven/Gradle项目,将Metadata文件夹移入src/main/resources目录,通过类加载器读取资源流:
public static ArrayList<String[]> loopCSV() throws DBAppException { try { String line; // 通过类加载器获取资源流,无需关心外部路径 try (InputStream is = loopCSV.class.getClassLoader().getResourceAsStream("Metadata/Metadata.csv"); BufferedReader br = new BufferedReader(new InputStreamReader(is))) { if (is == null) { throw new FileNotFoundException("Metadata/Metadata.csv not found in resources"); } ArrayList<String[]> TablesName = new ArrayList<>(); while ((line = br.readLine()) != null) { String[] r = line.split(","); TablesName.add(r); } return TablesName; } } catch (Exception e) { throw new DBAppException("can not read the csv file: " + e.getMessage()); } }
方法3:通过环境变量配置路径(高灵活性)
在不同环境中设置环境变量CSV_FILE_PATH指向目标文件,代码中读取该变量:
public static ArrayList<String[]> loopCSV() throws DBAppException { try { String line; // 读取环境变量中的文件路径 String csvPath = System.getenv("CSV_FILE_PATH"); if (csvPath == null || csvPath.isEmpty()) { throw new IllegalArgumentException("CSV_FILE_PATH environment variable not set"); } try (BufferedReader br = new BufferedReader(new FileReader(csvPath))) { ArrayList<String[]> TablesName = new ArrayList<>(); while ((line = br.readLine()) != null) { String[] r = line.split(","); TablesName.add(r); } return TablesName; } } catch (Exception e) { throw new DBAppException("can not read the csv file: " + e.getMessage()); } }
注意事项
- 确保目标文件存在且当前运行用户有读取权限;
- 优先使用try-with-resources语法管理文件流,避免资源泄漏。
内容的提问来源于stack exchange,提问作者Ahmed Haitham
相关产品推荐
相关产品推荐

