这是我报错的原来的代码
package day19.java2;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @ClassName FinallyTest3
* @Description TODO
* @Author CC
* @DATE 2022/4/12 11:15
* @Version 1.0
*/
public class FinallyTest3 {
public static void main(String[] args) {
FileInputStream fileInputStream = null;
try {
File file = new File("hello.txt");
fileInputStream = new FileInputStream(file);
int data = fileInputStream.read();
while (data != -1) {
System.out.print((char) data);
data = fileInputStream.read();
}
} catch (IOException e){
e.printStackTrace();
}finally {
try {
if (fileInputStream != null){
fileInputStream.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
}
我hello.txt在java2里面 如图
提示我找不到指定文件
尝试了很多次都不行,就干脆把hello.txt的绝对路径全部写到file里面
File file = new File("D:\\CC\\IDEA\\src\\day19\\java2\\hello.txt");
正常输出了
思考:在同一路径在为什么还要写绝对路径,不能写相对路径呢
把文件放在src下面
读取代码如下
public static void main(String[] args) throws Exception {
File file = new File("src/hello.txt");
FileInputStream fileInputStream = new FileInputStream(file);
int data = fileInputStream.read();
while (data != -1) {
System.out.print((char) data);
data = fileInputStream.read();
}
}
会发现是能读取成功的
原来idea好像你的类读取文件的时候路径默认是在模块下面的也就是在src同级的。要么将文件放最外面,要么前面跟好src/main/FinallyTest3/hello.txt。