My program can run with inputStream.toString(); but as you know thats not a good way to convert inputStream to String. So when I try to convert properly it hangs.
My methods are:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
if(initialized && connected){
try{
sms.findOperator();
jTextArea2.append(sms.logString);
sms.logString = "";
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Failed to find operator!", "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
else JOptionPane.showMessageDialog(null, "Cannot connect to the port specified!", "ERROR", JOptionPane.ERROR_MESSAGE);
// TODO add your handling code here:
}
This is the findOperator() method:
public void findOperator(){
send("AT+COPS?\r\n");
}
Here is send() method:
public void send(String cmd) {
try {
//Thread.sleep(200);
outputStream.flush();
outputStream.write(cmd.getBytes());
inputStream = serialPort.getInputStream();
//System.out.println(" Input Stream... " + inputStream.toString());
Thread.sleep(300);
logString += inputStreamtoString(inputStream);
}
catch(Exception e){
e.printStackTrace();
}
finally{
//logString += inputStream.toString()+ '\n';
// if(infoType == "msg") return "Input Stream... " + inputStream.toString()+ '\n';
// else return inputStream.toString();
//return logString;
//logString += inputStreamtoString(inputStream);
}
}
And this is the inputStreamtoString() method:
public String inputStreamtoString(InputStream is) throws IOException{
// try {
// return new java.util.Scanner(is).useDelimiter("\\A").next();
// } catch (java.util.NoSuchElementException e) {
// return "";
// }
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
If I don't use inputStreamtoString() method and use inputStream.toString() my program runs well, but I don't get proper String. Any suggestion?
Thanks in advance...
Update: My modem uses the port COM3 with a GSM SIM card. I get a String containing huge space, like:
+COPS: <...500 spaces...> 0,0,"Banglalink"
So I hate that spaces. I need a string : +COPS: 0,0,"Banglalink"
You are trying to read exhaustively (that is until all data is read) from a stream that is connected to a serial port. This will hang if there is no data available on the port (waiting for data to come). Even if there is data, you will have an infinite loop.
UPDATE:
You could try something like this instead (adapted from code listed here):
byte[] readBuffer = new byte[200];
try {
while (is.available() > 0) {
int numBytes = is.read(readBuffer);
sb.append(new String(readBuffer, "US-ASCII"));
}
} catch (IOException e) {
// handle exception
}
UPDATE: chaged the string creation to use a specified charset (instead of the system default)
Related
I am a beginner in android. I am trying to work on Sockets. But my InputStream is not reading the data as expected. It is getting out of the method after j = inputStream.read(arrayOfByte, 0, i); Please help me.
public void readinputstreamforid(final String ip, final int port){
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
try {
socket=new Socket(ip,port);
} catch (IOException e) {
e.printStackTrace();
}
final byte[] arrayOfByte = new byte[10000];
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
while (socket.isConnected()) {
int j = 0;
int i = arrayOfByte.length;
try {
j = inputStream.read(arrayOfByte, 0, i);
if (j == -1)
throw new IOException("not working");
if (j == 0)
continue;
} catch (IOException e) {
e.printStackTrace();
}
final String strData = new String(arrayOfByte, 0, j).replace("\r", "").replace("\n", "");
Log.d("hello","recieved: "+strData);
}
try {
IOUtils.write("!##\n",socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
asyncTask.execute();
}
If an error happens, you are logging it, but then you continue with the code, where more errors can then happen. When an error happens, STOP looping and exit the function. InputStream.read() returns -1 when the end of the stream is reached. For a socket, that means when the connection is closed. That is not really an error condition, so you don't need to throw an exception. Just break the loop. You can wrap the InputStream inside of a BufferedReader so you can use its readLine() method instead of reading bytes manually.
Also, you are trying to write to the socket's OutputStream after the socket has already disconnected. That will never work.
Try something more like this:
public void readinputstreamforid(final String ip, final int port){
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
try {
socket = new Socket(ip, port);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
OutputDataStream out = socket.getOutputStream();
do {
String data = in.readLine();
if (data == null)
break;
Log.d("hello", data);
IOUtils.write("!##\n", out, StandardCharsets.UTF_8);
}
while (true);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
asyncTask.execute();
}
try {
input = new BufferedReader(new InputStreamReader(
mSocket.getInputStream()));
while (!Thread.currentThread().isInterrupted()) {
String messageStr = null;
messageStr = input.readLine();
if (messageStr != null) {
updateMessages(messageStr, false);
} else {
break;
}
}
input.close();
} catch (IOException e) {
Log.e(CLIENT_TAG, "Server loop error: ", e);
}
I am using the above code in a thread for receiving responses from socket connection.
In Android it works correctly as I used out.println() for sending data, but when the device is connected to ios and starts to receive data it cannot identify the end and is only received when the connection is closed. Is there any alternative methods other than readLine() and how to use in the above code.
This would work better.
try
{
input = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
String messageStr = "";
while (!Thread.currentThread().isInterrupted() && (messageStr = input.readLine()) != null)
{
updateMessages(messageStr, false);
}
input.close();
} catch (Exception e) {
Log.e(CLIENT_TAG, "Server loop error: ", e);
}
In the method getFileName() created the object BufferedReader and assigned reference to the object to the variable - reader. Then stream closed in the finally.
Then invoked the method readStringsFromConsole(). There creates the same object. But thrown IOException. Why did it happen ?
ps: sorry for my English :)
stacktrace:
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:170)
at java.io.BufferedInputStream.read(BufferedInputStream.java:336)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at com.test.home04.Solution.readStringsFromConsole(Solution.java:55)
code:
import java.io.*;
import java.util.*;
public class Solution
{
public static void main(String[] args)
{
String fileName = getFileName();
ArrayList<String> listStrings = readStringsFromConsole();
writeToFileFromList(fileName, listStrings);
}
public static void writeToFileFromList (String fileName, ArrayList<String> listInputString)
{
PrintWriter writer = null;
try {
writer = new PrintWriter(fileName, "UTF-8");
for (String stringItem : listInputString)
writer.write(stringItem);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (writer != null)
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static ArrayList<String> readStringsFromConsole() {
BufferedReader reader = null;
ArrayList<String> listInputString = new ArrayList<String>();
String line = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
while (true)
{
line = reader.readLine();
if ("exit".equals(line))
break;
listInputString.add(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return listInputString;
}
}
public static String getFileName()
{
BufferedReader reader = null;
String fileName = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
while (fileName == null) {
fileName = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return fileName;
}
}
}
If you create a reader from System.in and close it, it also closes System.in, which can't be opened again even if you create another reader.
In short - don't close readers which are created from System.in.
Also as Andreas pointed out in the comment, the general guideline should be that System.in should only ever be wrapped once in the lifetime of the command-line program (whether by Scanner, BufferedReader, or something else), and it should never be closed. The wrapping should likely occur at the beginning of main(), and the wrapper object should either be passed around or stored in a field (static or instance).
Why did it happen ?
It happened because you closed System.in in your getFilename method.
Why not open the stream after the close?
Basically, because you can't, or if you are asking about the behavior of the JVM ... >>it<< can't.
When close() is called, the close gets sent to the operating system which closes and releases the underlying file descriptor. Once closed, the OS does not have enough information to reopen the previous file. And if the file descriptor was for an (unnamed) pipe or socket stream, then the connection cannot be remade because:
the application or service at the other end will typically have gone away,
in the case of a TCP/IP socket, the protocol does not allow reconnection.
In short: don't close a stream if you need to read or write more from / to it later, and avoid closing System.{in,out,err} entirely.
Now if your application had a filename or a host / port, it could open a new FileReader or connect a new socket. But in the case of the System.* streams, that information is not available to the application (or the JVM).
But in your particular case, I suspect that your intention is that getFileName returns the filenames supplied one at a time; i.e. each call returns the next filename. If that is the case, you will have to implement it differently:
It shouldn't close the stream or the reader.
It shouldn't open the reader (probably).
It should return the first (or next) line that it reads rather than reading all lines and returning the last one, as it currently does.
You are closing the stream from System.in. Closed stream needs to be opened before reusing it. Don't close them if you create them from System.in.
Try this,
import java.io.*;
import java.util.*;
public class Solution
{
public static void main(String[] args)
{
String fileName = getFileName();
ArrayList<String> listStrings = readStringsFromConsole();
writeToFileFromList(fileName, listStrings);
}
public static void writeToFileFromList (String fileName, ArrayList<String> listInputString)
{
PrintWriter writer = null;
try {
writer = new PrintWriter(fileName, "UTF-8");
for (String stringItem : listInputString)
writer.write(stringItem);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (writer != null)
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static ArrayList<String> readStringsFromConsole() {
BufferedReader reader = null;
ArrayList<String> listInputString = new ArrayList<String>();
String line = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
while (true)
{
line = reader.readLine();
if ("exit".equals(line)) {
break;
}
listInputString.add(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
//do not close the stream
//reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return listInputString;
}
}
public static String getFileName()
{
BufferedReader reader = null;
String fileName = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
while (fileName == null) {
System.out.println("Enter a file name: ");
fileName = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
//do not close the stream
//reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return fileName;
}
}
}
I i am able to read the lines from csv and download the images from url when the url is not having the image it is showing file not found exception in middle of the program i want to continue the program with out terminating.
public static void main(String[] args) throws IOException {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
BufferedReader br = new BufferedReader(new FileReader("D:\\imgdwnld\\file.csv"));
String line = br.readLine();
while ((line = br.readLine()) !=null){
URL url = new URL(line);
inputStream = url.openStream();
outputStream = new FileOutputStream("D:\\imgdwnld\\" +
line.substring(line.lastIndexOf("/")));
byte[] buffer = new byte[2048];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
} catch (MalformedURLException e) {
System.out.println("MalformedURLException :- " + e.getMessage());
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException :- " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException :- " + e.getMessage());
} finally {
try {
inputStream.close();
outputStream.close();
} catch (IOException e) {
System.out.println("Finally IOException :- " + e.getMessage());
}
}
}
This is the relevant outline of your code:
try {
...
while ((line = br.readLine()) !=null) {
... process each CSV line ...
}
} catch (IOException e) {
... handle it ...
}
At the place where you catch the exception you have already broken out of the main loop. Change the code to have this outline:
while ((line = br.readLine()) !=null) {
try {
... process one CSV line ...
} catch (IOException e) {
... handle it, the loop will proceed with the next line
}
}
You need to remove the "return" instruction from the corresponding catch (or maybe from the whole code). In your case, the instruction allows to "exit" the main method so the rest of instruction (those after the return statement) won't be executed.
Another tip is to separate this instructions in blocs. For example, if reading the CSV and the Img are not bound, you may need to encapsulate each treatment in an individual try-catch block. When parsing/reading the CSV file fails, your code may continue fetching the image.
I am trying to read the first line of a URL.
Then i want to use that as a string later in the code.
Anyone can help me?
I already tried it with
public static String main(String[] args) {
try {
URL url = new URL("myurlhere");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
return line;
}
in.close();
}
catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
return null;
}
I just can't get a string out of it.
You can consider using jsoup for your purpose:
try {
Document doc = Jsoup.connect("http://popofibo.com/pop/swaying-views-of-our-past/").get();
Elements paragraphs = doc.select("p");
for(Element p : paragraphs) {
System.out.println(p.text());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Output:
It is indeed difficult to argue over the mainstream ideas of evolution of human civilizations...
If you want to read from a file on the internet using a URL you should use URLConnection
here is a simple example:
String string = "";
try {
URLConnection connection = new URL(
"http://myurl.org/mypath/myfile")
.openConnection();
Scanner scanner = new Scanner(connection.getInputStream());
while (scanner.hasNext()) {
string += scanner.next() + " ";
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
// Do something with the string.