I would like to determine the number of bytes downloaded from the following working URL connection:
I have following code to implement:
.......
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream is = connection.getInputStream(); // throws an IOException
DataInputStream dis = new DataInputStream(new BufferedInputStream(is));
FileOutputStream fos = new FileOutputStream("C:\\Picture.jpeg");
int read =0;
byte[] bytes = new byte[1024];
while((read = dis.read(bytes)) != -1)
{
fos.write(bytes, 0, read);
}
System.out.println(read + " byte(s) copied");
The output from the last line is as follows:
Opening connection to http://www.xyz.com//Picture.jpeg...
Copying image resource (type: application/jpeg, modified on: 02/02/2010 4:19:21 AM)...
-1 byte(s) copied
What is the error of my code. please help me
int read =0;
int reddit = 0;
byte[] bytes = new byte[1024];
while((read = dis.read(bytes)) != -1)
{
fos.write(bytes, 0, read);
reddit += read;
}
//your read variable must have the value -1 at this point
System.out.println(reddit + " byte(s) copied");
int totalBytes = 0;
...
while((read = dis.read(bytes)) != -1)
{
totalBytes += read;
fos.write(bytes, 0, read);
}
Related
I'm sending a pdf file from my java server to an android client. However when I look at the pdf file on the phone, the text is sometimes wrong (just some random symbols). Does someone know what is causing that problem?
Here is the code of the server:
private void sendPdfToPhone(File pdf) {
try {
InputStream iS = new FileInputStream(pdf);
DataOutputStream dOS = new DataOutputStream(new BufferedOutputStream(this.clientSocket.getOutputStream()));
String filename = pdf.getName();
byte[] bytes = new byte[(int) pdf.length()];
dOS.writeUTF(filename);
dOS.writeLong(bytes.length);
byte[] buffer = new byte[8192];
int bytesRead;
int bytesSent = 0;
while ((bytesRead = iS.read(buffer)) > 0) {
dOS.write(buffer, 0, bytesRead);
bytesSent += bytesRead;
}
dOS.close();
logger.debug("Sent file " + filename + " to Client: " + bytesSent + " / " + bytes.length);
} catch (IOException ex) {
logger.fatal(ex);
}
}
And this is the code of the Android client:
int bytesRead;
String filename = dIS.readUTF();
long fileSize = dIS.readLong();
byte[] buffer = new byte[1024];
File pdf = new File(context.getCacheDir() + "/" + filename);
if (!pdf.exists()) {
pdf.createNewFile();
FileOutputStream fOS = new FileOutputStream(pdf);
while (fileSize > 0 && (bytesRead = dIS.read(buffer, 0, (int)
Math.min(buffer.length, fileSize))) != -1) {
fOS.write(buffer, 0, bytesRead);
fileSize -= bytesRead;
}
dIS.close();
dOut.close();
}
pdfFile = pdf;
socket.close();
return pdf;
I want to code a way to resume the download file in Java and show the progress if possible.
The following code was used to subtract the total size of the downloaded file (totalSize - downloaded) instead of completing the download.
URL url = new URL(urlFile);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
File SDCardRoot = Environment.getExternalStorageDirectory();
file = new File(SDCardRoot,"/MySchool/"+Folder+"/"+nameBook.getText().toString()+".pdf");
urlConnection.setRequestProperty("Range", "bytes=" + file.length() + "-");
urlConnection.setDoOutput(true);
urlConnection.connect();
outputStream = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
outputStream.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
outputStream.close();
This might be useful for pause and resume but please specify exact problem.
if (outputFileCache.exists())
{
connection.setAllowUserInteraction(true);
connection.setRequestProperty("Range", "bytes=" + outputFileCache.length() + "-");
}
connection.setConnectTimeout(14000);
connection.setReadTimeout(20000);
connection.connect();
if (connection.getResponseCode() / 100 != 2)
throw new Exception("Invalid response code!");
else
{
String connectionField = connection.getHeaderField("content-range");
if (connectionField != null)
{
String[] connectionRanges = connectionField.substring("bytes=".length()).split("-");
downloadedSize = Long.valueOf(connectionRanges[0]);
}
if (connectionField == null && outputFileCache.exists())
outputFileCache.delete();
fileLength = connection.getContentLength() + downloadedSize;
input = new BufferedInputStream(connection.getInputStream());
output = new RandomAccessFile(outputFileCache, "rw");
output.seek(downloadedSize);
byte data[] = new byte[1024];
int count = 0;
int __progress = 0;
while ((count = input.read(data, 0, 1024)) != -1
&& __progress != 100)
{
downloadedSize += count;
output.write(data, 0, count);
__progress = (int) ((downloadedSize * 100) / fileLength);
}
output.close();
input.close();
}
Self explanatory title, what is the int off from the android website, what does it do and why do i need it? I understand first and second argument from bytearrayoutputstream.write but not this one
from the android web:
OutputStream
Summary
void write(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to this output stream.
sample code:
public byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException(connection.getResponseMessage() +
": with " +
urlSpec);
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
off is short for "offset", which means the index to start copying from. That, combined with len (or "length"), allows you to copy an arbitrary subsequence instead of the entire source array. For example:
byte[] array = {1,2,3,4};
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(array, 1, 2); // copy 2 bytes from index 1
System.out.println(Arrays.toString(baos.toByteArray()));
// Output:
// [2, 3]
I want to read a file from a server and get the data of it.
I have written following piece of code.
URL uurl = new URL(this.m_FilePath);
BufferedReader in = new BufferedReader(new InputStreamReader(uurl.openStream()));
String str;
while ((str = in.readLine()) != null) {
text_file=text_file+str;
text_file=text_file+"\n";
}
m_byteVertexBuffer=text_file.getBytes();
But i am getting wrong result! If I read data from a string, I get m_bytevertexbuffer length=249664.
Now when I read a local file into the bytearray then i get m_bytevertexbuffer length=169332.
FileInputStream fis = new FileInputStream(VertexFile);
fis.read(m_byteVertexBuffer);
ByteBuffer dlb=null;
int l=m_byteVertexBuffer.length;
I want the same data in bytebuffer from a server and also from a local file!
If the server sends a header Content-Length: 999 you could allocate a new byte[999].
URL url = new URL("http://www.android.com/");
URLConnection urlConnection = url.openConnection();
int contentLength = urlConnection.getContentLength();
// -1 if not known or > int range.
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
//if (contentLength >= 0) {
// byte[] bytes = new byte[contentLength];
// in.read(bytes);
// m_byteVertexBuffer = bytes;
//} else {
ByteArrayOutputStream baos;
byte[] bytes = new byte[contentLength == -1 ? 10240 : contentLength];
for (;;) {
int nread = in.read(bytes, 0, bytes.length);
if (nread <= 0) {
break;
}
baos.write(bytes, 0, nread);
}
m_byteVertexBuffer = baos.toByteArray();
//}
} finally {
urlConnection.disconnect();
}
In the general case you would use only the code of the else-branch. But still, one the presence of a valid content-length it is usable.
I am trying to download/resume file. Resume seems to work, but whole download brings the problem. After executing this code testfile is 5242845. But it should be 5242880! I opened this two files in the hex editor and figured out that testfile missing some bytes at the end (begining is okay). This is the code:
String url = "http://download.thinkbroadband.com/5MB.zip";
String DESTINATION_PATH = "/sdcard/testfile";
URLConnection connection;
connection = (HttpURLConnection) url.openConnection();
File file = new File(DESTINATION_PATH);
if (file.exists()) {
downloaded = (int) file.length();
connection.setRequestProperty("Range", "bytes=" + (file.length()) + "-");
}
connection.setDoInput(true);
connection.setDoOutput(true);
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream fos = (downloaded == 0) ? new FileOutputStream(DESTINATION_PATH) : new FileOutputStream(DESTINATION_PATH, true);
BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
int x = 0;
int i = 0;
int lenghtOfFile = connection.getContentLength();
while ((x = in.read(data, 0, 1024)) != -1) {
i++;
bout.write(data, 0, x);
downloaded += x;
}
I think that the problem is here while ((x = in.read(data, 0, 1024)) != -1) {.
For example we have file 1030 bytes long. First write is good, bout.write(data,0,1024); but next time while ((x = in.read(data, 0, 1024)) != -1) { gets -1, because 1030-1024=6 bytes left. And we are trying to write 1024 bytes! I know it should not be so, but it seems that it is how I said. How can I figure this? Thanks.
bout.flush();
and/or
bout.close();
You need to close your BufferedOutputStream to ensure that all that is buffered is sent to the buffered OutputStream.
google told me, there is a "available" method of bufferedinputstream, so you can write like
(I´m not an java guru)
while (in.available() > 0)
{
x = in.read(data, 0, 1024);
bout.write(data, 0, x);
}