Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading line and splitting to char array

I can't understand why my program not functioning. It compiles but nothing is printed. I have a 5 character word in file. I need to read line from that file and then split it into char array, which I then want print out.Thanks!

import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;

public class test {
    public static void main(String[] args)
    {

        BufferedReader line = null;
        char[] array = new char[7];

        try{

            line = new BufferedReader(new FileReader(args[0]));

            String currentLine;
            while((currentLine = line.readLine()) != null)
            {
                array = currentLine.toCharArray();
            }

            for(int i = 0; i < array.length; i++)
            {
                System.out.print(array[i]);
            }

        }//try

        catch(IOException exception)
        {
            System.err.println(exception);
        }//catch

        finally
        {
            try 
            {
                if(line != null) 
                    line.close();
            }//try

            catch(IOException exception)
            { 
                System.err.println("error!" + exception);
            }//catch

        }//finally
    } // main
} // test
like image 453
Jack Morton Avatar asked Dec 21 '25 00:12

Jack Morton


1 Answers

Your while loop skips every line except the last one so it could be possible that your last line is empty. To display every line you could have:

while ((currentLine = line.readLine()) != null) {
    array = currentLine.toCharArray();
    for (int i = 0; i < array.length; i++) {
        System.out.print(array[i]);
    }
    System.out.println();
}

Or if you just have the 1 line, You could simply use:

String currentLine = line.readLine(); 
...
like image 77
Reimeus Avatar answered Dec 23 '25 13:12

Reimeus