我正在尝试检查文件内容是否为空。我有一个内容为空的源文件。 我尝试了不同的替代方法。但没有任何方法适合我。
这是我的代码:
Path in = new Path(source);
/*
* Check if source is empty
*/
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(in)));
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br.readLine().length() == 0) {
/*
* Empty file
*/
System.out.println("In empty");
System.exit(0);
}
else{
System.out.println("not empty");
}
} catch (IOException e) {
e.printStackTrace();
}
我试过使用 -
1. br.readLine().length() == 0
2. br.readLine() == null
3. br.readLine().isEmpty()
以上所有内容都不是空的。我需要使用 -
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(in)));
} catch (IOException e) {
e.printStackTrace();
}
代替 new File() 等
如果我哪里出错了,请指教。
编辑
Making little more clear. If I have a file with just whitespaces or without white space,I am expecting my result as empty.
最佳答案
您可以调用 File.length()
(返回此抽象路径名表示的文件的长度)并检查它是否不是 0
。有点像
File f = new File(source);
if (f.isFile()) {
long size = f.length();
if (size != 0) {
}
}
忽略空白(因为也是空)
你可以使用 Files.readAllLines(Path)
和类似的东西
static boolean isEmptyFile(String source) {
try {
for (String line : Files.readAllLines(Paths.get(source))) {
if (line != null && !line.trim().isEmpty()) {
return false;
}
}
} catch (IOException e) {
e.printStackTrace();
}
// Default to true.
return true;
}
关于java - 如何检查文件内容是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31800816/