2013-08-20 26 views
0

我想从服务器读取文件并获取其中的数据。如何从服务器中的字节数组中读取数据

我写了下面这段代码。

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长度= 249664。

现在,当我读取一个本地文件到bytearray然后我得到m_bytevertexbuffer长度= 169332。

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

ByteBuffer dlb=null; 

int l=m_byteVertexBuffer.length; 

我想从服务器和本地文件的bytebuffer中获得相同的数据!

+1

要读取字节,请从InputStream中读取,并且不要用Reader包装它。你的第二段代码没有意义:它打印出一个字节数组的长度,无论你是否从文件中读取,它都是相同的。阅读Java IO教程:http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html –

+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分支的代码。但是,仍然存在一个有效的内容长度是可用的。

+1

不保证read()方法会一次读取所有字节。应始终使用循环。 –

+0

urlConnection.disconnect()中有错误; –

+0

@MuneemHabib尝试'in.close();'。 –

相关问题