Reading strings from file to array of strings

Trying to read a set of strings and store each line of the text file into a string array entry

//FILE:

abcd

efgh

jklm

//TO...

String [] myString = {"abcd","efgh","jklm"};

The problem is that every time read from file and print the array..it only stores the first line of the text file in the array.

try{

FileReader theReader =new FileReader("Amaze.txt");

BufferedReader in =new BufferedReader(theReader);

String theLine;

theLine = in.readLine();

while ( theLine !=null ){

mazeString = theLine.split("\n");

theLine = in.readLine();

}

in.close();

}

catch (IOException e){// System.out.println("oops:\n" + e); }

}

[1184 byte] By [JoeDonea] at [2007-11-27 5:09:23]
# 1

You're acting as if the line you read is the whole file. The line you read won't have any \n's in it by definition, since it is a line! The file, however, will look like TEXT\nTEXT\nTEXT\n etc.

So there's no need to split it... every time you read a line just add it to your array or collection.

ktm5124a at 2007-7-12 10:29:07 > top of Java-index,Java Essentials,New To Java...
# 2

Thanks for the Reply.

I've applied what you recommended, but as i set the readline() to the array.. i get incompatible types exception.

String[] myArray;

while ( (in.readLine())!= null ) {

myArray= in.readLine();

}

Thanks in advance

JoeDonea at 2007-7-12 10:29:07 > top of Java-index,Java Essentials,New To Java...
# 3

You have to index an array when you initialize and/or refer to any given part of it.

String[] myArray = new String[10];

int i = 0;

while ( (in.readLine())!= null && i < myArray.length) {

myArray[i++] = in.readLine();

}

kevjavaa at 2007-7-12 10:29:07 > top of Java-index,Java Essentials,New To Java...
# 4
Why not use a list instead of an array? Who uses arrays anyway ;-)
Hippolytea at 2007-7-12 10:29:07 > top of Java-index,Java Essentials,New To Java...
# 5

> Why not use a list instead of an array? Who uses

> arrays anyway ;-)

True, true...

List<String> myList = new List<String>;

while ( (in.readLine())!= null) {

myList.add( in.readLine() );

}

kevjavaa at 2007-7-12 10:29:07 > top of Java-index,Java Essentials,New To Java...
# 6

I'm sure you meant:

String line

List<String> myList = new ArrayList<String>();

while ( (line = in.readLine())!= null) {

myList.add(line);

}

The repeated call to readLine is especially heinous.

Hippolytea at 2007-7-12 10:29:07 > top of Java-index,Java Essentials,New To Java...
# 7

> I'm sure you meant:

[snip]

> The repeated call to readLine is especially heinous.

doh...

I'm writing a psychic/telepathic compiler -- that was one of my test cases from earlier ;). I expect release sometime in 2015.

Besides, if you don't leave a bug in there every now and then, how are the newbies ever gonna learn to debug >:)?

kevjavaa at 2007-7-12 10:29:07 > top of Java-index,Java Essentials,New To Java...