如何在eclipse中获取conf.txt路径

时间:2013-06-25 21:25:17

标签: java eclipse path text-files workspace

我有一个eclipse项目,在一个文件夹中有一个文本文件“conf.txt”。当我在计算机上使用路径时,我可以读取和写入文件。但我必须在那里写我自己的文件夹,而不仅仅是工作区文件夹。 所以知道我想为其他人提交程序,但是我放入程序的路径将无法工作,因为程序在另一台计算机上运行。 我需要的是能够只使用我工作区中的路径文件。

如果我只是放入工作区中的路径,它就无法工作。

这是我的类文件的样子。

public class FileUtil {

public String readTextFile(String fileName) {

      String returnValue = "";
      FileReader file = null;

      try {
        file = new FileReader(fileName);
        BufferedReader reader = new BufferedReader(file);
        String line = "";
        while ((line = reader.readLine()) != null) {
          returnValue += line + "\n";
        }
        reader.close();
      } catch (Exception e) {
          throw new RuntimeException(e);
      } finally {
        if (file != null) {
          try {
            file.close();
          } catch (IOException e) {
            // Ignore issues during closing 
          }
        }
      }
      return returnValue;
    }

public void writeTextFile(String fileName, String s) throws IOException {

    BufferedWriter output = new BufferedWriter(new FileWriter(fileName));
    try {
        output.write(s);
    }
      finally {
        output.close();
      }
  }

}

我希望有人知道该怎么做。

谢谢!

2 个答案:

答案 0 :(得分:1)

我不确定,但我附上屏幕截图一点点解释。如果您有任何疑问,请与我联系。

您的项目是根文件夹,图像是资源文件夹,您可以使用相对路径访问该文件。

// looks for file in root --> file.txt
scan = new Scanner((new File("file.txt")));

// looks for file in given relative path i.e. root--> images--> file.txt
scan = new Scanner((new File("images/file.txt"))); 

enter image description here

答案 1 :(得分:0)

如果您希望通过相对路径访问配置文件,则不需要在其前面添加任何内容。假设你正在使用bufferedReader,或类似的东西,它看起来很简单:br = new BufferedReader(new FileReader("config.txt"));

这将导致搜索运行时目录,从而使您无需完全限定文件的路径。话虽这么说,你必须确保你的config.txt与你的可执行文件在同一个目录中。

相关问题