AM trying to download a file from the net using the url & urlconnection class in java using this code.
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(destination);
} catch (FileNotFoundException ex) {
}
try {
URL url = null;
try {
url = new URL("here is the url");
//
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
URLConnection urlc = null;
try {
urlc = url.openConnection();
System.out.println("Conneceted");
} catch (IOException ex) {
ex.printStackTrace();
}
try {
bis = new BufferedInputStream(urlc.getInputStream());
} catch (IOException ex) {
ex.printStackTrace();
}
bos = new BufferedOutputStream(fos);
// System.out.println("absolute path="+destination.getAbsolutePath());
int i;
try {
while ((i = bis.read()) != -1) {
System.out.print((char) i);
bos.write(i);
}
JOptionPane.showMessageDialog(this, "downloadeded sucessfully");
this.dispose();
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "could not be diownloaded \n please try again");
ex.printStackTrace();
}
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
When i run this code on my windows system it runs perfectly but when i take my code to mac os it gives me the exception
Exception in thread "Thread-2" java.lang.NullPointerException
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
at java.io.FilterOutputStream.close(FilterOutputStream.java:140)
at FileDownloader.Download(FileDownloader.java:201)
at FileDownloader$2.run(FileDownloader.java:114)
at java.lang.Thread.run(Thread.java:637)
Could anyone tell me what the reason may be? and how i can solve this?
Thanks in advance
Related
This code is used to copy an instance through java serialization. It uses the traditional try-catch-finally writing method. Can it be changed to try-with-resources form?(The DeepConcretePrototype in the code is an ordinary java object)
/**
* Clone an instance through java serialization
* #return
*/
public DeepConcretePrototype deepCloneBySerializable() {
DeepConcretePrototype clone = null;
ByteArrayOutputStream byteArrayOutputStream = null;
ObjectOutputStream objectOutputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
ObjectInputStream objectInputStream = null;
try {
//Output an instance to memory
byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(this);
objectOutputStream.flush();
//Read instance from memory
byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
objectInputStream = new ObjectInputStream(byteArrayInputStream);
clone = (DeepConcretePrototype)objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (objectOutputStream != null) {
try {
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (byteArrayInputStream != null) {
try {
byteArrayInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return clone;
}
Yes you can use try-with-resources, but it's a little tricky because the success of read depends on the success of write. One way you can write it is with a nested try:
public DeepConcretePrototype deepCloneBySerializable() {
DeepConcretePrototype clone = null;
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
//Output an instance to memory
objectOutputStream.writeObject(this);
objectOutputStream.flush();
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
//Read instance from memory
clone = (DeepConcretePrototype) objectInputStream.readObject();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return clone;
}
I am using a FileOutputStream to create a file in an activity that is not my MainActivity. The file is created, and when I destroy the activity, the data I want is written, but when I relaunch the activity from my MainActivity, the file cannot be found. What can I change in my code so that I don't get a fileNotFoundException? The relevant code is here:
try {
fis = new FileInputStream("words");
ois = new ObjectInputStream(fis);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
EOFException eof = null;
int counter = 0;
if (fnfexception == null) {
while (eof == null) {
try {
if (words == null) words = new Dict[1];
else words = Arrays.copyOf(words, counter + 1);
words[counter] = (Dict) ois.readObject();
counter++;
} catch (EOFException end) {
eof = end;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
wordStartCount = counter;
wordCount = counter;
fnfexception = null;
try {
fos = openFileOutput("words", Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
You used wrong way to read from an internal file, use the following code
try {
FileInputStream fis = context.openFileInput("file_name");
int content;
StringBuilder str = new StringBuilder();
while ((content = fis.read()) != -1)
str.append((char) content);
fis.close();
String savedText = str.toString();
} catch (IOException e) {
e.printStackTrace();
}
I am uploading a file from one server to another server using a Java Program 'POST' method. But I am getting below exception.
java.io.IOException: Error writing to server
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:582)
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:594)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1216)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)
at com.test.rest.HttpURLConnectionExample.TransferFile(HttpURLConnectionExample.java:107)
at com.test.rest.HttpURLConnectionExample.main(HttpURLConnectionExample.java:44)
I have other method who will authenticate with server. Which will be be called from below code. When I am getting response from server, I am getting above exception. To Transfer a file to server I have written below method. My sample code is below:
public static void TransferFile(){
String urlStr = "http://192.168.0.8:8600/audiofile?path=1/622080256/virtualhaircut.mp3";
File tempFile = new File("/home/MyPath/Workspace/Sample/virtualhaircut.mp3");
BufferedWriter br=null;
HttpURLConnection conn = null;
URL url;
try {
url = new URL(urlStr);
AuthenticationUser();
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", new MimetypesFileTypeMap().getContentType(tempFile.getName()));
} catch (MalformedURLException e1) {
System.out.println("Malformed");
e1.printStackTrace();
} catch (ProtocolException e) {
System.out.println("Protocol");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO");
e.printStackTrace();
}
System.out.println("line 69");
FileInputStream fis;
OutputStream fos;
try {
System.out.println("line 75");
System.out.println("line 77");
fis = new FileInputStream(tempFile);
fos = conn.getOutputStream();
byte[] buf = new byte[1024 * 2];
int len = 0;
System.out.println("line 80");
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
System.out.println("line 85");
}
System.out.println("line 87");
buf = null;
fos.flush();
fos.close();
fis.close();
}catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (conn.getResponseCode() == 200) {
System.out.println("here");
}
} catch (IOException e) {
e.printStackTrace();
}
}
It is possible that the error ocurred because the receiving server closed the connection, maybe because your file exceeded the size limit. Have you tested with small files?
My idea is that I want to read an object from a serialized file located in a server. How to do that?
I can only read .txt file using the following code :
void getInfo() {
try {
URL url;
URLConnection urlConn;
DataInputStream dis;
url = new URL("http://localhost/Test.txt");
// Note: a more portable URL:
//url = new URL(getCodeBase().toString() + "/ToDoList/ToDoList.txt");
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
dis = new DataInputStream(urlConn.getInputStream());
String s;
while ((s = dis.readLine()) != null) {
System.out.println(s);
}
dis.close();
} catch (MalformedURLException mue) {
System.out.println("Error!!!");
} catch (IOException ioe) {
System.out.println("Error!!!");
}
}
You can do this with this method
public Object deserialize(InputStream is) {
ObjectInputStream in;
Object obj;
try {
in = new ObjectInputStream(is);
obj = in.readObject();
in.close();
return obj;
}
catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
feed it with urlConn.getInputStream() and you'll get the Object. DataInputStream is not fit to read serialized objets that are done with ObjectOutputStream. Use ObjectInputStream respectively.
To write an object to the file there's another method
public void serialize(Object obj, String fileName) {
FileOutputStream fos;
ObjectOutputStream out;
try {
fos = new FileOutputStream(fileName);
out = new ObjectOutputStream(fos);
out.writeObject(obj);
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
Here is the code I am trying to send SMS through the red Oxygen server
Here is the code I am executing below
final String requestURL = "http://www.redoxygen.net/sms.dll?Action=SendSMS";
final StringBuilder stringBuilder = new StringBuilder();
try {
stringBuilder.append("AccountId=").append(URLEncoder.encode("****", "UTF-8"))
.append("&Email=").append(URLEncoder.encode("*******", "UTF-8"))
.append("&Password=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Recipient=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Message=").append(URLEncoder.encode("hello", "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
final URL address;
try {
address = new URL(requestURL);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
final HttpURLConnection connection;
try {
connection = (HttpURLConnection) address.openConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new RuntimeException(e);
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(100000000);
DataOutputStream output = null;
try {
output = new DataOutputStream(connection.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
output.writeBytes(stringBuilder.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
While executing I am getting the below exception :
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:525)
at sun.net.NetworkClient.doConnect(NetworkClient.java:158)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:323)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:860)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:801)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:904)
at com.nextenders.server.LoginServlet.SendSMS(LoginServlet.java:143)
I tried with increasing connection timeout and turn off the firewall ...etc but no luck .Can anyone help me to trace the problem ??
Here is the tutorial I'm following :
http://www.redoxygen.com/developers/java/
The "*"s in my code is credentials for the gateway .
This is a network topology problem. You can't connect to that site from where you are. Some intervening firewall, probably your own, is preventing it. Talk to your netadmin.
The following code runs fine when I have tested it with other websites (as I don't have access your the messaging API):
final String requestURL = "http://www.redoxygen.net/sms.dll?Action=SendSMS";
final StringBuilder stringBuilder = new StringBuilder();
try {
stringBuilder.append("AccountId=").append(URLEncoder.encode("****", "UTF-8"))
.append("&Email=").append(URLEncoder.encode("*******", "UTF-8"))
.append("&Password=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Recipient=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Message=").append(URLEncoder.encode("hello", "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
final URL address;
try {
address = new URL(requestURL);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
final HttpURLConnection connection;
try {
connection = (HttpURLConnection) address.openConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new RuntimeException(e);
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(100000000);
try {
connection.connect();
} catch (IOException e) {
throw new RuntimeException(e);
}
final DataOutputStream output;
try {
output = new DataOutputStream(connection.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
output.writeUTF(stringBuilder.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
final InputStream inputStream;
try {
inputStream = connection.getInputStream();
} catch (IOException e) {
final char[] buffer = new char[0x10000];
final StringBuilder stackBuilder = new StringBuilder();
final Reader in;
try {
in = new InputStreamReader(connection.getErrorStream(), "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
try {
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read > 0) {
stackBuilder.append(buffer, 0, read);
}
} while (read >= 0);
System.out.println("Error response code from server. Error was:");
System.out.println(stackBuilder.toString());
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
try {
in.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
throw new RuntimeException(e);
}
final char[] buffer = new char[0x10000];
final StringBuilder stackBuilder = new StringBuilder();
final Reader in;
try {
in = new InputStreamReader(inputStream, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
try {
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read > 0) {
stackBuilder.append(buffer, 0, read);
}
} while (read >= 0);
System.out.println(stackBuilder.toString());
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
try {
in.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
It will toString the various streams and has error handling when the stream doesn't connect.
The most important change is using the DataOutputStream.writeUTF method rather than just the write method - this will ensure than the POST data is encoded correctly. I don't think this is your issue as the problem is on connect.
The example code you used seems to be unaware of Java naming conventions or best practices to I have tidied it considerably.
The stream reader can be pulled out and into a separate method to avoid duplication.
I would recommend pointing it at another website (I used my work's) and seeing if you get output.