java - java - 如何从特定行读取文件到另一个特定行?


System.out.println("Escriba el ID Del Cliente");


 CL.setID(reader.next());


 String line2;


 int count = 0;


 try {


 BufferedReader input = new BufferedReader(new FileReader(file));


 Scanner input2 = new Scanner(file);


 PrintWriter output = new PrintWriter(new FileOutputStream(file, true));


 LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));



 while((line2 = input.readLine()) != null)


 {



 if(line2.contains(CL.getID()))


 {


 while(((line2 = readers.readLine()) != null) && readers.getLineNumber() <= count + 3)


 {


 count++;


 System.out.println(line2);



 }



 input.close();


 input2.close();


 output.close();


 readers.close();


 break;


 }



 }



 }catch(IOException ex)


 {


 System.out.println("ERRORR!!!!!!");


 }



时间:

现在,为了使程序正常工作,你需要使用BufferedReaderLineNumberReader


public static void main(String[] args) {


 System.out.println("Escriba el ID Del Cliente");


 String line2;


 File file = new File(yourpathhere);


 int lineCount = 0;


 try {


 PrintWriter output = new PrintWriter(new FileOutputStream(file, true));


 LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));


 while ((line2 = readers.readLine()) != null) {


 lineCount++;


 if (line2.contains(CL.getId())) {


 while (line2 != null && readers.getLineNumber() <= lineCount + 3) {


 System.out.println(line2);


 line2 = readers.readLine();


 }


 output.close();


 readers.close();


 break;


 }


 }



 } catch (IOException ex) {


 System.out.println("ERRORR!!!!!!");


 }


 }



假设有一个包含100行的文件,并且想要检查并打印出第5行到10行,你可以尝试:


System.out.println("Escriba el ID Del Cliente");


CL.setID(reader.next());


String line;


int count = 0;


int xLine = 5;


int yLine = 10;


try (BufferedReader input = new BufferedReader(new FileReader(file)))


{


 while((line = input.readLine()) != null)


 {


 if(count < xLine)


 {


 // skip all lines lower then start


 continue;


 }


 else if(count >= xLine && count <= yLine && line.contains(CL.getID()))


 {


 // print line if line is between lines to read


 // and if line contains ID


 System.out.println(line);


 }


 else


 {


 // break if count is bigger then yLine


 break;


 }


 count++;


 }


}


catch(IOException ex)


{


 System.out.println("ERRORR!!!!!!");


}



检查行是否包含你的ID,然后增加已处理行的计数。

...