I am following some tutorial vids and learning how to read files with java. In this example the instructor creates a char array sized to 100 and then uses the FileReader class to read a text file and place the characters is the char array, and then System.out the array to the console. My code is the same as the instructor but my output includes square symbols to fill up the 100 char array, while the instructors output shows the char array correctly.
Here is the code snippet and output
import java.io.*;
public class MSReader
{
public static void main(String[] args)
{
// the character stream lasses when working
// with char or strings [ reader, writer]
char[] array = new char[100];
try
{
Reader reader = new FileReader(
"C:\\Users\\ricky\\OneDrive\\Desktop - Lenovo Laptop\\test\\InputStreamExample.txt");
// check if reader is ready
System.out.println("Ready: " + reader.ready());
// reading the characters
reader.read(array);
System.out.println("Data in the stream: ");
System.out.println(array);
// close stream
reader.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Output I get: output
The instructors output doesnt show the square symbols. When I copy and paste the symbols to this site, it doesnt show up either so I had to take a screenshot of it.
You have an array:
Any time you create an array with particular size, it is initialized with the default values of its type. So, your array has default values in it and the default value of
charis '\u0000' (the null character), which is printed as some weird rectangle that you see.After that, you have a code:
which reads input into provided array (i.e. reads input and stores that in the array). So, it fills the array from the beginning (0 index) with the content that is in the file (one character per one slot of the underlying array), and if the number of characters in the file is less than the number of slots of the provided array, you have a remainder, that is the slots with their initial (default) values in it.