这个问题在这里已有答案:
编辑:我已经找到了解决这个问题的方法,它与MS90评论非常相似。由于我的工作目录是“ATM项目”,因此java只能注意到我在该目录中给出的相对路径。将我的路径名更改为“group_0331 \ phase1 \ deposits.txt”就可以了,因为“group_0331”在我当前的目录中。现在,在阶段1下创建了我想要的文件。
我需要能够将此文件(和读取)写入与具有createAccount方法的java文件相同的目录。所以不是工作目录。此外,我无法对路径名进行硬编码,因为此文件不会始终从同一台计算机运行。我怎样才能做到这一点?
void createAccount(String name, String accountType){
try {
accounts = new File("accounts.txt");
Writer writer = new BufferedWriter(new FileWriter(accounts, true));
writer.write(String.format("%s \naccounts: %s", name, accounts));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
你问的是不可能的:当你的程序运行时,'java'文件不存在; java将java文件编译为类文件,然后运行它们。
如果要从与类文件相同的位置加载accounts.txt,请使用以下命令:
public class ExampleClass {
// catching an exception and calling printStackTrace is bad code. Do not do this.
void example() throws IOException {
try (InputStream in = ClassYouAreIn.class.getResourceAsStream("accounts.txt")) {
// you can read it here.
}
}
}
你不能写信给它;类文件通常位于无法写入的位置(例如,jar文件)。
“我希望将文件写入与我的类文件相同的位置”的概念是一个非常糟糕的主意。如果您必须编写文件,请为文件选择一个合理的位置,然后使用它。一些例子: