How to read a java file

I want to read a file, here is my code:

import java.io.*; 
public class ReadFromFile
{ 
  public static void main(String[] args)throws Exception 
  { 
  File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt"); 

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

  String st; 
  while ((st = br.readLine()) != null) 
    System.out.println(st); 
  } 
} 

Thank you in advance.

1 answer

  • answered 2020-03-25 13:58 Eritrean

    I am not sure I realy understand what you are trying to achieve. A better sample input file and the expected output could make your question easier to understand. But I assume your problem is the second for loop:

       String part;
    
       //....
    
       for (Element div : myDivs) {
          part = div.text();  
          System.out.println(part);
       }
    

    You overwrite your variable part with each iteration. At the end your variable part will only contain the text of the last div. To change that you should concatenate the text of each div by changing the loop to something like:

    for (Element div : myDivs) {
       part = part + " " + div.text();  
       // or add a new line to separte the divs 
       // part = part + "\n" + div.text();  
       System.out.println(part);
    }