Scinder Scinder - 1 year ago 110
Java Question

Copying Files into Arrays (Java)

I am trying to read into a file, make it into an array and print it.

I'm not sure what I'm doing wrong with this code. I've been trying to get a solution but all the solutions I can find are more advanced than what we should be using...I wrote a previous program using the same method but as a Double array. I can't seem to make it work for a String?

I keep getting [Ljava.lang.String;@3d4eac6 when I run it.

I just want it to print boysNames. boyNames.txt is just a list of 200 names in a text file.

Someone please help me, or let me know if this is possible?

this is my code so far

public static void main(String[] args) throws FileNotFoundException {

String[] boyNames = loadArray("boyNames.txt");

public static String[] loadArray(String filename) throws FileNotFoundException{
//create new array
Scanner inputFile = new Scanner(new File (filename));
int count = 0;
//read from input file (open file)
while (inputFile.hasNextLine()) {
//close the file

String[] array = new String[count];
//reopen the file for input
inputFile = new Scanner(new File (filename));
for (int i = 0; i < count; i++){
array[i] = inputFile.nextLine();
//close the file again
return array;


Answer Source

Java arrays don't override Object.toString(), so you get a generic [Ljava.lang.String;@3d4eac6 (or similar) when you try to print it out using System.out.println(). Instead loop over the array and print each value.

for (String boyName : boyNames) {

Alternatively, you could use Arrays.toString():


Another alternative would be to use String.join() (new for Java 8)

System.out.println(String.join("\n", boyNames));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download