Illep
Illep

Reputation: 16851

Reading a String array from a BufferedReader

I am implementing a client server application. from the server i am sending a String array, and now i want to read whats in that string array from my client code. How can i do this;

When i print the value from the client i get the output something like [Ljava.lang.String;@120d10

server:

try {
                    PrintWriter r= (PrintWriter) i.next();

                    String[] s={"f","ff"};
                    r.println(s);

                    r.flush();
                } catch (Exception ex) {

                }

client:

try {
                    while ((somestring= r.readLine()) != null) {
                        //When i print it i get something like [Ljava.lang.String;@120d10


                    }
                } catch (Exception ex) {}

Upvotes: 2

Views: 703

Answers (4)

rtcarlson
rtcarlson

Reputation: 424

You're trying to println the array of strings, instead of each string in the array. Try something like this on the server:

    try {
                PrintWriter r= (PrintWriter) i.next();

                String[] s={"f","ff"};
                for(String sElement : s)
                {
                    r.println(sElement);
                    r.flush();
                }

            } catch (Exception ex) {

            }

Upvotes: 1

SJuan76
SJuan76

Reputation: 24885

r.println(object) calls object.toString() to know what to print. The arrays stringTo() method return just that value ([L means you are dealing with an array).

If you want to print all the array, loop it.

for(String  str : s) {
  r.println(str + delimiter);
}

Of course, you will have to find a valid delimiter (one that does not appear inside your strings).

Upvotes: 2

Aleksander Blomskøld
Aleksander Blomskøld

Reputation: 18552

You should consider using ObjectOutputStream / ObjectInputStream instead. Then you can send all kinds of Serializable objects (including arrays) directly.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533530

When you print an array, it call toString() on it first. The default toString() for an array prints the type @ hashCode which is generally useless.

What you intended was something like

String[] arr={"f","ff"};
for(String s: arr)
    r.println(s);

Upvotes: 3

Related Questions