1
我有下面的類,擴展線程。 這個想法是提取線程內的日期,並且一切順利,直到接收到的數據大於幾千字節爲止,然後我開始讀取完整的不正確數據。讀取不正確的值?
public class ThreadBooksPositions extends Thread
{
public ThreadBooksPositions()
{
}
..
// default constructors
public void run()
{
InputStream iSS = null;
HttpURLConnection connection = null;
Integer sectionsDescriptorSize1 = 0;
Integer sectionsDescriptorSize2 = 0;
try
{
URL url = new URL("192.168.1.4/bookstore.asp?getbooks");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
iSS = connection.getInputStream();
BufferedInputStream bIS = new BufferedInputStream(iSS);
if(bIS.available() > 4)
{
Float lat = 0F;
Float lng = 0F;
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] bf;
try
{
bf = new byte[ bIS.available() ];
while (bIS.read(bf) != -1)
out.write(bf); //copy streams
out.flush();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} //you can configure the buffer size
byte[] bO = out.toByteArray();
if(out != null)
{
try
{
out.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ByteBuffer data = ByteBuffer.wrap(bO);
sectionsDescriptorSize1 = data.getInt();
sectionsDescriptorSize2 = data.getInt();
ByteBuffer sectionData;
try
{
if(sectionsDescriptorSize1 > 0)
{
byte[] bAS0 = new byte[ sectionsDescriptorSize1 ];
data.get(bAS0);
}
if(sectionsDescriptorSize2 > 1)
{
// trajectory
byte[] bAS1 = new byte[ sectionsDescriptorSize2 ];
data.get(bAS1, 0, sectionsDescriptorSize2);
sectionData = ByteBuffer.wrap(bAS1);
Boolean readingFailed = true;
if(sectionData != null)
{
while(sectionData.available() > 1)
{
try
{
readingFailed = false;
lat = sectionData.getFloat(); // 4
lng = sectionData.getFloat(); // 4
}
catch(Exception e)
{
readingFailed = true;
}
try
{
if(readingFailed == false)
{
addBookStorePosition(lat, lng);
}
}
catch (Exception e)
{
}
}
}
}
catch(Error e)
{
}
}
}
catch(IOException e)
{
}
finally
{
if(iSS != null)
{
try
{
iSS.close();
}
catch(IOException e)
{
}
}
if(connection != null)
{
connection.disconnect();
}
}
}
}
- 什麼可能導致不正確讀取數據?
你有調試嗎? –
您的代碼難以閱讀,因爲一切都在一種方法內。嘗試將run()中的代碼拆分爲不同的方法是一個好主意。順便說一句,我認爲你最好將這個問題遷移到http://codereview.stackexchange.com/ – nakosspy
@nakosspy代碼審查是審查實際工作的代碼,而不是修復不起作用的代碼。如果您不知道其他網站的用途,請不要告訴其他網站。 – svick