2013-08-20 28 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();'。 –

相關問題