0

I am trying to create an android client and java server application using socket programming. I need to retrieve the file send from java server but i dont want to write that content into another file in client side. Instead i want to create a listbox with the contents in the received file. I can find code for write these contents in a file but I dont know how to access the contents as strings.

Here is the code i tried:

Android client

client=new Socket("10.0.2.2", 7575);
writer=new PrintWriter(client.getOutputStream(),true);
writer.write(mMsg);
writer.flush();
writer.close();
InputStream is=client.getInputStream(); 
bytesread=is.read(mybytearray,0,mybytearray.length);

I changed my code as follws but it is not working.

 InputStream is=client.getInputStream();
 BufferedReader bf=new BufferedReader(new InputStreamReader(is));
 String value=bf.readLine();

3 Answers 3

1

Wrap your inputstream into a BufferedReader

BufferedReader d
          = new BufferedReader(new InputStreamReader(is));

and use readLine() method.

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

InputStream is=client.getInputStream(); 
bytesread=is.read(mybytearray,0,mybytearray.length);
// Create a new String out of the bytes read
String data = new String(mybytearray, 0, bytesread, CharSet);

OR

Wrap the InputStream using BufferedReader and read the data line by line (using readLine()) in String format.

2 Comments

when i give the above code it give an error that CharSet is not resolved to a type. What i need to give? pls give any suggestion
@user3243259: Refer this docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html. For now you can pass it as "UTF-8"
0

Using buffered reader is best or you can try the code below:

After the last statement use the byte[] "mybytearray" to convert to string as below:

if(bytesread > 0)
    String result = new String(mybytearray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.