我有以下代码要读取带有一堆键/值对的文件,我知道该键存在并且不为空。但是,当我运行它时,我看到我的“行为空” printf。有指针吗?我是一名菜鸟Java程序员。
String oldContent = "";
File fileToBeModified = new File("/some_path/gradle.properties");
try (BufferedReader reader = new BufferedReader(new FileReader(fileToBeModified))) {
//Reading all the lines of input text file into oldContent
String line = reader.readLine();
if (line == null) {
System.out.println("line is null");
}
while (line != null) {
if (line.contains("version=")) {
oldVersion = line;
}
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
if (oldContent.isEmpty()) {
System.out.println("file is empty");
}
}
catch(...) {
...
}
该文件具有(这是gradle.properties文本文件),并且具有0644个权限。
group=com.mycompany.mygroup
s3_bucket=war-uploads/maven/repository
#DO NOT REMOVE: Random number(256161) to force rebase from master if necessary.
version=1.0.0
此代码有效:
String oldContent = "";
String fileToBeModified = "c://temp//gradle.properties";
try (BufferedReader reader = new BufferedReader(new FileReader(fileToBeModified))) {
//Reading all the lines of input text file into oldContent
String line = reader.readLine();
if (line == null) {
System.out.println("line is null");
}
while (line != null) {
if (line.contains("version=")) {
String oldVersion = line;
}
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
if (oldContent.isEmpty()) {
System.out.println("file is empty");
}
}
catch(Exception e) {
e.printStackTrace();
}