简体   繁体   中英

How to read data from file in server in byte array

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM