如何确定使用PrintWriter打开文件的正确路径?

时间:2019-03-17 22:12:20

标签: java file printwriter

创建PrinterWriter对象时:

PrintWriter outputFile = new PrintWriter(*FileName*);

寻找 FileName 的编译器在哪里?例如,在Eclipse中,我正在使用 Arrays / src / ArraysAndFiles.java 。在此示例中,我尝试打开 Values.txt 。我已经在 src 目录中创建了该文件,因为该文件存储了 ArraysAndFiles.java 。当我尝试使用以下代码打开文件时,出现FileNotFoundException

import java.io.PrintWriter;

public class ArraysAndFiles {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        PrintWriter outputFile = new PrintWriter("Values.txt");

    }
}

Values.txt 的正确路径是什么?

3 个答案:

答案 0 :(得分:0)

Solution #1 (recommended for small files but you have the benefit that file will be found in other computers as well): How do I load a file from resource folder?

Solution #2: Build the path step by step by using File(String parent, String child) constructor. Example:

File desktop = new File(System.getProperty("user.home"),"Desktop");
File textsFolder = new File(desktop,"texts");
File testsFolder = new File(textsFolder,"tests");
File peopleTxt = new File(testsFolder,"people,txt");

Which is equals to: C://Users//George//Desktop//texts//tests//people.txt (Windows OS).

答案 1 :(得分:-1)

In your example "Values.txt" is a relative path. It's relative to your working directory.
Usually it's the same directory where your JAR file resides.

In Eclipse an application is built in the 'bin' folder. In your case it's Arrays\bin\. So this is the working directory for the application and your file has to be there.

If you want Eclipse to export this file during the Build process, do the following:

Right click on the file -> Build Path -> Add to Build Path

答案 2 :(得分:-1)

As per code,

PrintWriter outputFile = new PrintWriter("Values.txt");

if you place your Values.txt in current/project directory i.e. in Arrays folder it should work but there are limitation as mentioned in above comments like writing to the file which is a part of JarFile.

Depending upon your purpose, you should take the action.