Reputation: 31
I am writing a desktop app in Java to upload a file to a folder on IIS server using HTTP PUT.
URLConnection urlconnection=null;
try{
File file = new File("C:/test.txt");
URL url = new URL("http://192.168.5.27/Test/test.txt");
urlconnection = url.openConnection();
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
if (urlconnection instanceof HttpURLConnection) {
try {
((HttpURLConnection)urlconnection).setRequestMethod("PUT");
((HttpURLConnection)urlconnection).setRequestProperty("Content-type", "text/html");
((HttpURLConnection)urlconnection).connect();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
BufferedOutputStream bos = new BufferedOutputStream(urlconnection
.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
int i;
// read byte by byte until end of stream
while ((i = bis.read()) >0) {
bos.write(i);
}
System.out.println(((HttpURLConnection)urlconnection).getResponseMessage());
}
catch(Exception e)
{
e.printStackTrace();
}
try {
InputStream inputStream;
int responseCode=((HttpURLConnection)urlconnection).getResponseCode();
if ((responseCode>= 200) &&(responseCode<=202) ) {
inputStream = ((HttpURLConnection)urlconnection).getInputStream();
int j;
while ((j = inputStream.read()) >0) {
System.out.println(j);
}
} else {
inputStream = ((HttpURLConnection)urlconnection).getErrorStream();
}
((HttpURLConnection)urlconnection).disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This program creates an empty file on the destination folder (Test). The contents are not written to the file.
What is wrong with this program?
Upvotes: 3
Views: 14313
Reputation: 10052
Possible bug: bis.read() can return a valid 0. You'll need to change the while condition to >= 0.
Upvotes: 1
Reputation: 16528
After you complete the loop where you are writing the BufferedOutputStream
, call bos.close()
. That flushes the buffered data before closing the stream.
Upvotes: 5