为 csv 文件使用动态路径

Using a Dynamic path for a csv file

我有一个保存在文件上的程序。当前代码设置为文件保存在特定路径上,但是当我 运行 来自不同计算机的程序时,该程序不起作用,我每次都需要更改路径。

 public CreateCustomer() {
    initComponents();

    ArrayList<String> ConsIDList = new ArrayList<String>();

    String csvFileToRead = "E:\ryan_assignment_sit2\ConsID\consID.csv"; // Reads the CSV File. 
    BufferedReader br = null; // Creates a buffer reader.
    String line = "";
    String splitBy = ","; // Reader Delimiter

    try {
        br = new BufferedReader(new FileReader(csvFileToRead)); // Buffer Reader with file name to read.
        Scanner reader = new Scanner(System.in);
        while ((line = br.readLine()) != null) { //While there is a line to read.
            reader = new Scanner(line);
            reader.useDelimiter(splitBy);

            while (reader.hasNext()) { // While there is a next value (token).
                ConsIDList.add(reader.next());
            }
        }

    } catch (FileNotFoundException exception) { // Exception Handler if the File is not Found.
        exception.printStackTrace();
    } catch (IOException exception) { // Input/Output exception
        exception.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close(); // Close the Scanner.
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }

我将文件放在名为 ConsID 的程序的子文件夹中,并尝试将路径文件更改为

String csvFileToRead = "..\ConsID\consID.csv"; 

但是无法从程序中读取文件。

字符串 csvFileToRead = "E:\ryan_assignment_sit2\ConsID\consID.csv"; 以上路径将只适用于windows。如果您在 linux 环境中执行该程序,您将得到 Filenotfoundexception。尽管您更改了文件,但您还是在对文件路径进行硬编码。 更好的是,您可以将其作为运行时参数获取,以便无论 OS.

如何执行程序

如果您 运行 从命令行编程,那么您可以将 csv 文件放在 class 路径中(生成 class 文件的根文件夹)并参考如下所示:

BufferedReader br = new BufferedReader(ClassLoader.getResourceAsStream("consID.csv"));