我测试一个示例代码,它显示了异常管理的使用,并以文本文件为例。我的问题是我不知道该存档的默认位置在哪里创建它。这是代码:package exceptionManager;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;
public class CheckedExceptionDemo {
public static void main(String[] args) {
//Below line calls readFile method and prints content of it
String filename="test.txt";
try {
String fileContent = new CheckedExceptionDemo().readFile(filename);
System.out.println(fileContent);
} catch (FileNotFoundException e) {
System.out.println("File:"+ filename+" is missing, Please check file name");
} catch (IOException e) {
System.out.println("File is not having permission to read, please check the permission");
}
}
public String readFile(String filename)throws FileNotFoundException, IOException{
FileInputStream fin;
int i;
String s="";
fin = new FileInputStream(filename);
// read characters until EOF is encountered
do {
i = fin.read();
if(i != -1) s =s+(char) i+"";
} while(i != -1);
fin.close();
return s;
}}
3 回答

12345678_0001
TA贡献1802条经验 获得超5个赞
文件名实际上是一个相对路径 - 它不包含任何驱动器号,也不以/
或开头\
。它从您当前的工作目录开始解析。此目录取决于您实际启动程序的方式。
例如,如果从命令行提示符运行java,则当前所在的目录是基本目录。如果您cd
到另一个目录,程序将在那里搜索该文件。
如果从IDE启动程序,则工作目录的默认文件夹是项目的基目录。但是,您可以在运行配置中更改此设置。
如果没有任何帮助,请尝试从程序中打印目录,例如:
System.out.println("Current dir: " + new java.io.File( "." ).getCanonicalPath())
添加回答
举报
0/150
提交
取消