【问题标题】:Issues reading a text file in the same folder as the JAR program读取与 JAR 程序位于同一文件夹中的文本文件时出现问题
【发布时间】:2015-11-23 16:11:41
【问题描述】:

我在 .jar 程序所在的位置有一个文本文件:

主文件夹:

|_ myJar.jar

|_ myText.txt

当我运行 .jar 文件时,我希望它读取 myText.txt 的内容,但是将路径设置为 String fileName = "./Paths.txt"; 它仍然无法读取该文件。我相信它正在尝试从 jar 中读取 Paths.txt 文件。

我尝试了其他解决方案,似乎没有人告诉程序从 jar 文件外部读取 Paths.txt 文件,因此非常感谢任何帮助。

代码:

public static void readFile() { 

    String fileName = "./Paths.txt"; 
    BufferedReader br; 
    String line; 
    //Attempts to read fileName
    try { 
        br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
        try { 
            // Starts reading the file and adding values to linked hashmap
            while ((line = br.readLine()) != null) { 
                String[] lineSplit1 = line.split("#"); 
                String lineKey = lineSplit1[0]; 
                String lineValue = lineSplit1[1]; 
                hm.put(lineKey, lineValue);
            }
        } catch(Exception e3) { 
            errorMessage("Error when trying to read the file and add "
                    + "the values to a hashmap"); 
        }
        //Attempts to close fileName
        try {
            br.close();
        } catch(IOException e1 ) { 
            System.out.println("Messed up while trying to close buffered reader"); 
            System.out.println(e1); 
        }
    } catch (FileNotFoundException e1) { 
        errorMessage("The file " + fileName + " does not exist" 
                 + "\nI have created the file for you."); 
        try {  
            PrintWriter writer = new PrintWriter(fileName, "UTF-8");
            writer.println("");
            writer.close();
        } catch(Exception e2) { 
            errorMessage("Error while trying to create " + fileName);
        }
    }
}

【问题讨论】:

  • 使用System.getProperty("user.dir") 或new File(".") 并将结果打印到控制台以确保工作目录与您期望的位置相同...您也可以使用@987654325 @ 测试是否存在,这可以帮助..

标签: java file text jar


【解决方案1】:

我想,您可以获得文件的完整路径,只需要通过您的 Class 初始化它,该 Class 应该打包在 myJar.jar 中。只需将示例中的 YourClass 更改为 jar 中的某个真实 Class。

public static void readFile() { 
  File file = new File(YourClass.class.getProtectionDomain().getCodeSource().getLocation().getFile());        
  String fileName = file.getParent() + File.separator + "Paths.txt";
...

【讨论】:

    猜你喜欢
    • 2013-02-04
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多