输入:
bank_details
payee
online_system_id
transaction_id
pass_num
prev_tran_approved
bank_details
payee
online_system_id
transaction_id
prev_tran_approved
以下代码的实际输出。
bank_details
payee
online_system_id
transaction_id
pass_num
prev_tran_approved
online_system_id
proc_online_system_id
tran_reversed
prev_tran_approved
bank_details
payee
online_system_id
transaction_id
prev_tran_approved
online_system_id
proc_online_system_id
tran_reversed
prev_tran_approved
预期产出:
bank_details
payee
online_system_id
transaction_id
pass_num
prev_tran_approved
proc_online_system_id
tran_reversed
bank_details
payee
online_system_id
transaction_id
prev_tran_approved
proc_online_system_id
tran_reversed
以下代码仅供参考。 即使文件中不存在字符串,我检查文件中现有字符串的if条件总是返回true。请仔细检查代码并建议我进行更改。
好的逻辑是我们必须读取一个包含各行的文件,其中每条记录都以空行分隔。取决于我在if块中提到的条件,即字符串online_system_id是否已经存在于文件中我们不会追加它,如果它不存在,那么我们将在每个记录块的末尾附加它。此检查将针对4个值执行,即online_system_id,proc_online_system_id,tran_reversed,prev_tran_approved
String line;
File output = new File(outputDir, "post_tran.tbl");
PrintStream out = new PrintStream(new FileOutputStream(output));
BufferedReader br = new BufferedReader(new FileReader(inputFile));
while((line=br.readLine())!=null){
if(line.trim().isEmpty()) {
if(!(line.contains("online_system_id"))){
out.println("online_system_id");
}
if(!(line.contains("proc_online_system_id"))){
out.println("proc_online_system_id");
}
if(!(line.contains("tran_reversed"))){
out.println("tran_reversed");
}
if(!(line.contains("prev_tran_approved"))){
out.println("prev_tran_approved");
}
}
out2.println(line); //always print the current line
}
try{
out2.close();
br.close();
} catch (Exception ex) {
System.err.println(ex);
}
答案 0 :(得分:4)
编辑:
在解释了你的逻辑后,看起来你需要跟踪当前记录中出现的4个特殊字符串中的哪一个,并在记录结束时添加其中没有的字符串。你可以使用4个布尔变量来完成它。
boolean osi = false;
boolean posi = false;
boolean tr = false;
boolean pta = false;
while((line=br.readLine())!=null){
if(line.trim().isEmpty()) {
// end of record, print each of the 4 special Strings that didn't appear
if(!osi){
out.println("online_system_id");
}
if(!posi){
out.println("proc_online_system_id");
}
if(!tr){
out.println("tran_reversed");
}
if(!pta){
out.println("prev_tran_approved");
}
osi = false;
posi = false;
tr = false;
pta = false;
} else {
// track appearance of the 4 special Strings
if(line.contains("online_system_id")){
osi = true;
}
if(line.contains("proc_online_system_id")){
posi = true;
}
if(line.contains("tran_reversed")){
tr = true;
}
if(line.contains("prev_tran_approved")){
pta = true;
}
}
out.println(line); //always print the current line
}
答案 1 :(得分:0)
变化
if(line.trim().isEmpty())
到
if(!line.trim().isEmpty())
也:
if((line.contains("online_system_id"))){
out.println("online_system_id");
}
if((line.contains("proc_online_system_id"))){
out.println("proc_online_system_id");
}
if((line.contains("tran_reversed"))){
out.println("tran_reversed");
}
if((line.contains("prev_tran_approved"))){
out.println("prev_tran_approved");
}