创建 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 的正确路径是什么?
最佳答案
解决方案#1(建议用于小文件,但您也可以在其他计算机中找到该文件):How do I load a file from resource folder?
解决方案 #2:使用 File(String Parent, String child)
构造函数逐步构建路径。示例:
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");
等于:C://Users//George//Desktop//texts//tests//people.txt(Windows 操作系统)。
关于java - 如何确定使用 PrintWriter 打开文件的正确路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55212461/