meallhour meallhour - 1 month ago 5
Java Question

How to print char array that is being read from a file?

I have a file

abc.txt
within directory
abc


I am trying to read the file using the following code:

File dir1 = new File("abc");
File fileread = new File(dir1, "abc.txt");
FileReader fr = new FileReader(fileread);

char[] ch = new char[(int)fileread.length()];

fr.read(ch);
System.out.println("File values are:");
System.out.print(Arrays.toString(ch));

fr.close();


I am getting a blank output like below:

[ , , , , ]

Answer

Maybe you should test if you really have got the content from file; I run these code and get the char array code like this

    File dir1 = new File("/Users/Laily");
    File fileread = new File(dir1, "abc.txt");
    FileReader fr = new FileReader(fileread);

    char[] ch = new char[(int)fileread.length()];

    fr.read(ch);
    System.out.println("File values are:");
    System.out.print(Arrays.toString(ch));
    fr.close();

this is the output:

File values are:
[t, h, i, s,  , i, s,  , a,  , t, e, s, t, ]

Hope this can help you...

Comments