我有4个文本文件a.txt,b.txt,c.txt和c.txt 我有一个从a.txt获取行的编码,如果条件如下,那么我还有另一个条件可以从b,c或d(它跟随条件)进一步获取
import java.io.*;
public class Scholarship {
public static void main(String[] args) {
try{
FileInputStream fstream1 = new FileInputStream("a.txt");
FileInputStream fstream2 = new FileInputStream("b.txt");
FileInputStream fstream3 = new FileInputStream("c.txt");
FileInputStream fstream4 = new FileInputStream("d.txt");
DataInputStream in1 = new DataInputStream(fstream1);
DataInputStream in2 = new DataInputStream(fstream2);
DataInputStream in3 = new DataInputStream(fstream3);
DataInputStream in4 = new DataInputStream(fstream4);
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
BufferedReader br3 = new BufferedReader(new InputStreamReader(in3));
BufferedReader br4 = new BufferedReader(new InputStreamReader(in4));
String strLine1=null;
String strLine2=null;
String strLine3=null;
String strLine4=null;
while((strLine1 = br1.readLine()) != null){
String[] column1 = strLine1.split("\\|");
if(Integer.parseInt(column1[1])<5000) {
while((strLine2 = br2.readLine())!=null){
String[] column2 = strLine2.split("\\|");
if( (column1[0].equals(column2[0]))&&(column2[2].equals("mumbai"))&&( (column2[3].equals("C"))||(column2[3].equals("D")) ) ){
System.out.println(strLine2);
}//if ends
}//while ends
while((strLine3 = br3.readLine())!=null){
String[] column3 = strLine3.split("\\|");
if( (column1[0].equals(column3[0]))&&(column3[2].equals("mumbai"))&&( (column3[3].equals("C"))||(column3[3].equals("D")) ) ){
System.out.println(strLine3);
}//if ends
}//while ends
while((strLine4 = br4.readLine())!=null){
String[] column4 = strLine4.split("\\|");
if( (column1[0].equals(column4[0]))&&(column4[2].equals("mumbai"))&&( (column4[3].equals("C"))||(column4[3].equals("D")) ) ){
System.out.println(strLine4);
}//if ends
}//while ends
}//if ends
}//while ends
in1.close();
in2.close();
in3.close();
in4.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
外部循环用于b,c和d的a.txt和内部3循环。代码仅在a.txt中满足第一个条件时打印。它不会检查a.txt中的线路。我用Scanner方法尝试过,但同样存在问题。
答案 0 :(得分:0)
除非您有意阅读原始Java数据类型(参见http://docs.oracle.com/javase/7/docs/api/java/io/DataInputStream.html),否则不应使用DataInputStream
。
您可以像这样实例化BufferedReader
阅读器:
BufferedReader br1 = Files.newBufferedReader(Paths.get("a.txt"), StandardCharsets.UTF_8);
或传统上喜欢这样:
BufferedReader br1 = new BufferedReader(new FileReader("a.txt"));
最后,您可以关闭所有BufferedReaders。它们将隐式地关闭所有包含的流。