如何从字节数组中的服务器中的文件读取数据

时间:2013-08-20 13:00:09

标签: java android file bytebuffer

我想从服务器读取文件并获取它的数据。

我写了以下一段代码。

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();

但我的结果错了!如果我从字符串中读取数据,我会得到m_bytevertexbuffer length = 249664。

现在当我将一个本地文件读入bytearray时,我得到m_bytevertexbuffer length = 169332。

FileInputStream fis = new FileInputStream(VertexFile);
fis.read(m_byteVertexBuffer);

ByteBuffer dlb=null;

int l=m_byteVertexBuffer.length;

我希望来自服务器和本地文件的bytebuffer中的数据相同!

1 个答案:

答案 0 :(得分:0)

如果服务器发送标头Content-Length: 999,您可以分配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();
}

在一般情况下,您只使用else-branch的代码。但仍然存在一个有效的内容长度,它是可用的。