How to access data in InputStream as String? - java

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();

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.

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.

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);

Related

DataInputStream printing unknown character from a socket

I'm getting an unknown character when reading from a socket using DataInputStream. When I send "Hello" on the server side the output is "Hello" the unknown character is the issue. I'm new to socket programming so I don't know what the issue could be. I tried using a BufferReader and PrintWriter too bu the server when using readLine() does not print the text sent but rather java.io.BufferedReader.
Server Side:
//BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataInputStream is= new DataInputStream(socket.getInputStream());
String userinput= is.readLine();
System.out.println("Client message: "+userinput);
Client Side:
//BufferedReader std= new BufferedReader(new InputStreamReader(System.in));
String userInput;
DataOutputStream out;
while((userInput=std.readLine()) !=null){
Socket socketClient= new Socket("localhost",5000);
OutputStream os= socketClient.getOutputStream();
out=new DataOutputStream(os);
out.writeUTF(userInput);
out.flush();
socketClient.close();
}
You're using writeUTF on the client side, are you sure readLine on the server side is compatible with it? I had never seen that before, but the javadoc mentions it's a "modified" UTF-8 encoding. Try using readUTF instead, or simply use the regular write method.
If you read a UTF line then you can write UTF or ASCII characters but as opposed to if you read ASCII characters then you must write those characters as ASCII.
try to use out.write(userInput); instead of out.writeUTF(userInput);

How to close FTPClient FileStream properly

I'm reading the content from a file located on a server with the FTPClient from Apache Commons Net. It works fine when only reading once. But when I'm trying to read a second file, the InputStream of my FTPClient returns null. This is my code:
FTPClient ftpClient = new FTPClient();
ftpClient.connect("myhostname");
ftpClient.login("myusername", "mypassword");
// read InputStream from file
InputStream inputStream = ftpClient.retrieveFileStream("/my/firstfile.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
// read every line...
// close everything
inputStream.close();
bufferedReader.close();
// second try
inputStream = ftpClient.retrieveFileStream("/my/secondfile.txt");
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
// ...
inputStream.close();
bufferedReader.close();
What am I doing wrong?
After closing the InputStream, do the following:
ftpClient.completePendingCommand();
You can find more information in the javadoc of FTPClient#retrieveFileStream:
To finalize the file transfer you must call completePendingCommand and check its return value to verify success. If this is not done, subsequent commands may behave unexpectedly.

How to read unicode characters from server socket

I need to receive a unicode (UTF-8) string sent by client on a server side. The length of the string is of course unknown.
ServerSocket serverSocket = new ServerSocket(567);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
I can read bytes using in.read() (until it returns -1) but the problem is that the string is unicode, in other words, every character is represented by two bytes. So converting the result of read() which would work with normal ascii characters makes no sense.
update
As per suggestions bello, I created the reader as follows:
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),"UTF-8"));
I've changed the client side to send a newline (#10#13) after each string.
But the new problem is I get bullshit instead of real string if i call:
in.readLine();
And print the result I get some nonsense string (I cannot even copy it here) although I am not dealing with non-latin chars or anything else.
To see what's going on I introduced following code:
int j = 0
while (j < 255){
j++;
System.out.print(in.read()+", ");
}
So here I just print all bytes received. If I send "ab" I get:
97, 0, 98, 0, 10, 13,
This is what one would expect, but than why the readLine method doesn't produce "good" results?
Anyway, if we couldn't find the actual answer, I should probably collect the bytes (like above) and create my string from them? How to do that?
P.S. Just a quick note - I am on windows.
Use new InputStreamReader(clientSocket.getInputStream(), "UTF-8") in order to set properly the name of the charset to use while reading the InputStream coming from your client
When creating InputStreamReader you can set encoding like this:
BufferedReader in =
new BufferedReader(
new InputStreamReader(clientSocket.getInputStream(), "UTF-8")
);
Try this way:
Reader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream(), StandardCharsets.UTF_8));
Note the StandardCharsets class. It is supported since Java 1.7 and provides more elegant way to specify a standard encoding like UTF-8.

Wrting a HTTP proxy in Java using only the Socket class

I'm trying to write an HTTP proxy in Java using only the Socket class. I had attempted to construct one earlier, and I was successfully sending a request by writing to the socket's output stream But I am having a hard time reading the response. the research I have conducted suggests that I should use the input stream and read it line by line, but I have not been able to read any web-pages successfully using this method. Would anyone have any suggestions as to where I could go from here?
My code actually uses a byte buffer to read from the input stream in order to read the page in bytes:
InputStream input = clientSocket.getInputStream()
byte[] buffer = new byte[48*1024];
byte[] redData;
StringBuilder clientData = new StringBuilder();
String redDataText;
int red;
while((red = input.read(buffer)) > -1) {
redData = new byte[red];
System.arraycopy(buffer, 0, redData, 0, red);
redDataText = new String(redData, "UTF-8");
System.out.println("Got message!! " + redDataText);
clientData.append(redDataText);
}
If you are asking for a way to read an InputStream by lines, this one may serve you:
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(input, "UTF-8"));
String line;
StringBuilder clientData=new StringBuilder();
while ((line=bufferedReader.readLine()) != null)
{
clientData.append(line);
}
You have to be careful not to read an InputStream in this fashion unless you are a priori sure that it contains just plain text (and not binary data).
BTW: For shake of efficiency, I recommend you to pre-size the clientData with an initial size according to the final size (if not, it will start from a default size of 10, and will need to be re-sized more times).

display the output-stream of a Process returned by Runtime.exec()

How do I print to stdout the output string obtained executing a command?
So Runtime.getRuntime().exec() would return a Process, and by calling getOutputStream(), I can obtain the object as follows, but how do I display the content of it to stdout?
OutputStream out = Runtime.getRuntime().exec("ls").getOutputStream();
Thanks
I believe you are trying to get the output from process, and for that you should get the InputStream.
InputStream is = Runtime.getRuntime().exec("ls").getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader buff = new BufferedReader (isr);
String line;
while((line = buff.readLine()) != null)
System.out.print(line);
You get the OutputStream when you want to write/ send some output to Process.
Convert the stream to string as discussed in Get an OutputStream into a String and simply use Sysrem.out.print()

Categories