Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am using the above code to print the lines of a file. The problem is the line only appears for a millisecond. My file only contains a single line of length 70,000 and I want to split it on some substring and then write it to a different file with multiple lines as an output. I also tried saving the read string to an array list inside the while loop.
Java
ArrayList  ArrayList lis = new ArrayList()
lis.add(l)
Also,
Java
lis.size()
It shows that the string is successfully copied to the array list.
Java
lis.get(0).length()
It shows the length of the string inside the list. But some how I can't read the string neither in the code below nor in SysOut.
Java
System.out.println(lis.get(0))
I am not sure what I am doing wrong. Also I tried the above code with some other text file with multiple lines, it works. Ignore the errors in the code above(if any), I typed it here. Thanks!

What I have tried:

public static void main(String args[]) {
    String l = null;
    try{
        File file = new File("sample.txt");
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        int i = 0;
        while((l = br.readLine()) != null){
            System.out.println(l);
        }
        br.close();
    }
    catch(FileNotFoundException e){
        System.out.println("File Not Found");
    }
    catch(IOException ex){

    }
}
Posted
Updated 9-May-18 7:28am
v2

1 solution

Java
while((l = br.readLine()) != null){

The first time this is called it reads that line into variable l, which you then display. The next time it is called, the end of file is reached, so readLine returns null, and the program terminates.

You need to do some more processing each time you receive a non-null line of text.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900