You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java主程序通过命令行参数读取指定文件夹内文件的方法

Java读取命令行参数指定路径下的metadata.csv文件

实现步骤

  1. 构建完整文件路径:基于传入的文件夹路径,拼接metadata.csv文件名,推荐用java.nio.file.Paths类处理,自动适配不同操作系统的路径分隔符。
  2. 读取并输出文件内容:使用Java IO类读取文件,采用try-with-resources语法自动关闭资源,避免内存泄漏。

完整代码示例

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class TestFilLesing{

    public static void main (String[] args){
        String folderPath = null;
        if (args.length > 0) {
            folderPath = args[0];
            // 拼接metadata.csv的完整路径
            Path metadataPath = Paths.get(folderPath, "metadata.csv");
            String filePath = metadataPath.toString();

            // 读取文件内容并逐行输出
            try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                System.err.println("读取文件出错: " + e.getMessage());
            }
        } else {
            System.out.println("未提供文件夹路径。");
        }
    }
}

Java 8+简化写法

如果使用Java 8及以上版本,可通过Files.lines进一步简化读取逻辑:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class TestFilLesing{

    public static void main (String[] args){
        String folderPath = null;
        if (args.length > 0) {
            folderPath = args[0];
            Path metadataPath = Paths.get(folderPath, "metadata.csv");

            try (Stream<String> lines = Files.lines(metadataPath)) {
                lines.forEach(System.out::println);
            } catch (IOException e) {
                System.err.println("读取文件出错: " + e.getMessage());
            }
        } else {
            System.out.println("未提供文件夹路径。");
        }
    }
}

注意事项

  • 跨平台兼容:Paths.get()会自动处理Windows的\和Linux/macOS的/路径分隔符,避免手动拼接出现的兼容性问题。
  • 资源自动回收:try-with-resources语法会在代码块结束后自动关闭IO资源,无需手动调用close()。
  • 异常排查:捕获IOException并输出错误信息,可快速定位文件不存在、权限不足等问题。

内容的提问来源于stack exchange,提问作者user21564783

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 01:25:07