【发布时间】:2021-06-24 14:37:04
【问题描述】:
我编写了一个代码来从目录中读取文件。
该目录包含许多文件。首先,我计算目录中的文件数,然后我想计算文件中扩展名为.info和.data的行数
我的代码如下:
public void checkEmptyEntryFileLoader(String directory) {
File name = new File(directory);
String filenames[]=name.list();
long countFile = 0;
long countLineData = 0;
long countLineInfo = 0;
for(String filename:filenames){
//System.out.println(filename);
countFile++;
}
System.out.println(countFile); // this bloc worked well
File files[]=name.listFiles();
for(File file:files){
String fileName = file.getName();
if(fileName.endsWith("data")) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
while (reader.readLine() != null) {
countLineData++;
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fileName.endsWith("info")) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
while (reader.readLine() != null) {
countLineInfo ++;
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(countLineInfo );
}
}
我得到了错误:
java.io.FileNotFoundException: my_file_name.data (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
错误涉及the FileReader,它只接受string,而filename 是String
你有什么想法吗? 谢谢
【问题讨论】:
-
我认为你应该使用
getPath或getAbsolutePath而不是getNamebaeldung.com/java-path -
File.getName 返回a path which is different from the File object’s path。
标签: java bufferedreader filereader