0

i'm new in Java/Android. I create an array like this:

String [] resultArray = new String [lengthFromServ];
                int i = 0;      
                while (i<lengthFromServ) {
                    int result = fromServ.read();
                    char valueOfResult = (char) result;
                    String resultFromServ = Character.toString(valueOfResult);
                    resultArray[i] = resultFromServ;
                    i++;
                }

lengthFromServ is declared before:(while statement executes 4 times)

lengthFromServ = 4;

Serwer send me string: "0,12"

When I try print elements of this array by:

System.out.println(Arrays.toString(resultArray))

I get:

[0, ,, 1, 2]

My question is: how can I get only elements of this array ? Without "[", "]", "," ? I just want to get this string:

0,12

Please help, I would be grateful for any help.

4

2 回答 2

1

您正在从服务器读取完全错误的方式。您应该使用 BufferedReader 或 DataInputStream。这些将使您轻松阅读:

Socket socket = new Socket(serverHost, serverPort);
DataInputStream dis = new DataInputStream(socket.getInputStream());
int lengthFromServer = 4;
byte resultArray[] = new byte[lengthFromServer];
dis.readFully(result);
String result = new String(resultArray);

或者,如果您的服务器将在内容之后添加换行符,您可以更轻松地做到这一点:

Socket socket = new Socket(serverHost, serverPort);
DataInputStream dis = new DataInputStream(socket.getInputStream());
String result = dis.readLine();
于 2013-08-17T18:03:29.870 回答
0
final String resultArrayString = Arrays.toString(resultArray);
System.out.println(resultArrayString.substring(1, resultArrayString.length()-1).replace(" ", "");

我的回答是基于这样一个假设,即您的主要目的只是以您想要的格式打印出数组。

于 2013-08-17T18:00:10.127 回答