读取与JAR程序位于同一文件夹中的文本文件的问题

时间:2015-08-28 22:15:47

标签: java file text jar

我的文本文件与我的.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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

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

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