2012-04-21 69 views
-2

我有自定义套接字客户端服务器。现在,当我传输二进制文件时,有些字节会转换为超出范围的字符。所以我用十六进制字符串发送它们。这样可行。但是对于另一个问题,这不是解决方案。通过套接字或http下载图像

当我从网上下载图片时,会发生同样的事情。有些字节变成别的东西。我按字节比较了字节。 转换为字符串显示?而不是符号。我曾试过读者和字节数组输入流。我已经在网上尝试过所有的例子。我可以做什么错误?

更新(回答接受):

检查您发送或接收对象的哑剧。如果它是一个二进制文件,请使用InputStream | OutputStream和派生类,当文本时,使用Reader |作家和派生类。

不要使用读者和作家下载的二进制文件,像我一样(文本这只作品,然后你必须使用十六进制字符串,增加了性能问题):

void saveFile(String strFileName){ 


try{ 
     URL url = new URL(strImageRoot + strFileName); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); 
     BufferedWriter bw = new BufferedWriter(new FileWriter(strImageDownloadPath + strFileName)); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      bw.write(line); 
     } 
    }catch(FileNotFoundException fnfe){ 
     System.out.println("FileNotFoundException occured!!!"); 
    }catch(IOException ioe){ 
    }catch(Exception e){ 
     System.out.println("Exception occured : " + e); 
    }finally{ 
     System.out.println("Image downloaded!!!"); 
    } 
} 
+2

发表您的代码.. – 2012-04-21 06:07:28

回答

1

使用此代码

  File root = android.os.Environment.getExternalStorageDirectory();    

      File dir = new File (root.getAbsolutePath() + "/image"); 
      if(dir.exists()==false) { 
       dir.mkdirs(); 
      } 

      URL url = new URL("http://4.bp.blogspot.com/-zqJs1fVcfeY/TiZM7e-pFqI/AAAAAAAABjo/aKTtTDTCgKU/s1600/Final-Fantasy-X-Night-Sky-881.jpg"); 
      //URL url = new URL(DownloadUrl); 
      //you can write here any link 
      File file = new File(dir,"Final-Fantasy-X-Night-Sky-881.jpg"); 



      long startTime = System.currentTimeMillis(); 


      //Open a connection to that URL. 
      URLConnection ucon = url.openConnection(); 


      //* Define InputStreams to read from the URLConnection. 

      InputStream is = ucon.getInputStream(); 
      BufferedInputStream bis = new BufferedInputStream(is); 


      //* Read bytes to the Buffer until there is nothing more to read(-1). 

      ByteArrayBuffer baf = new ByteArrayBuffer(6000); 
      int current = 0; 
      while ((current = bis.read()) != -1) { 
       baf.append((byte) current); 
      } 


      //Convert the Bytes read to a String. 
      FileOutputStream fos = new FileOutputStream(file); 
      fos.write(baf.toByteArray()); 
      fos.flush(); 
      fos.close(); 
+0

感谢。本文有助于理解何时使用以及何时从其他位置下载文件:http://docs.oracle.com/javase/tutorial/essential/io/file.html – 2014-07-31 06:29:21

0

当我构建一个Socket客户端服务器应用程序时,我遇到了类似的问题。字节将是一些奇怪的字符,我尝试了各种各样的事情来尝试和比较它们。然后我遇到了一个讨论,其中some1指出我应该使用datainputstream,dataoutstream,并让它进行字节间的转换。完全为我工作。我从来没有触及过字节。