Unm*_*eni 4 java hadoop mapreduce file bufferedreader
我正在尝试检查文件内容是否为空。我有一个内容为空的源文件。我尝试了不同的选择。但没有什么对我有用。
这是我的代码:
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();
}
Run Code Online (Sandbox Code Playgroud)
我试过使用 -
1. br.readLine().length() == 0
2. br.readLine() == null
3. br.readLine().isEmpty()
Run Code Online (Sandbox Code Playgroud)
以上所有内容都不是空的。我需要使用 -
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(in)));
} catch (IOException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
而不是 new File() 等。
如果我在某处出错,请指教。
编辑
再清楚一点。如果我有一个只有空格或没有空格的文件,我希望我的结果为空。
您可以调用File.length()(返回此抽象路径名表示的文件长度)并检查它是否不是0。就像是
File f = new File(source);
if (f.isFile()) {
long size = f.length();
if (size != 0) {
}
}
Run Code Online (Sandbox Code Playgroud)
你可以使用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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15151 次 |
| 最近记录: |