如何逐行打印对象

时间:2014-08-07 06:10:46

标签: java eclipse object text

我有以下代码:

 in = new BufferedReader(new FileReader("D/sample.txt"));
  String str;   
  while ((str = in.readLine()) != null) 
  {  
      process(str);
  }

假设sample.txt包含'n'行数。我将String对象传递给同一个类中的另一个函数进程。函数进程包含以下代码:

public void process(String s) {
String elements = s;
System.out.println(elements);

如何仅打印第一行或我希望打印的行。请帮忙。

4 个答案:

答案 0 :(得分:0)

您可以将标志传递给您的流程方法,以建议它是否打印。像这样:

public void process(String s, boolean print) {
String elements = s;
if(print)
   System.out.println(elements);

}

答案 1 :(得分:0)

如果我理解你,你可以传入lineCount - 即

in = new BufferedReader(new FileReader("D:/sample.txt")); // <-- added ':'
String str;   
int lineCount = 0;
while ((str = in.readLine()) != null) {  
  process(str, lineCount++);
}

然后

public void process(String s, int lineCount) {
  if (lineCount == 0) { // <-- only the first line.
    System.out.println(s);
  }
}

答案 2 :(得分:0)

只需在循环中添加一个计数器,并且只对要处理的行调用进程。

in = new BufferedReader(new FileReader("D/sample.txt"));
String str;   
int readLines = 0;
while ((str = in.readLine()) != null) 
{   
    readLines++;
    if(readLines == 1) //Only process first line
     process(str);
}

答案 3 :(得分:0)

仅针对您希望的行呼叫process(str)

int lineToPrint = 1;

in = new BufferedReader(new FileReader("D/sample.txt"));
  String str;   
  int i =1;
  while ((str = in.readLine()) != null) 
  {  
     if (i==1){
         process(str);
     }
     i++;
  }