2012-04-21 7 views
-2

私はカスタムソケットクライアントサーバーを持っています。バイナリファイルを転送すると、いくつかのバイトが範囲外の文字に変換されます。だから私は16進数の文字列でそれらを送信します。それは動作します。しかし、別の問題では、これは解決策ではありません。ソケットまたはhttpで画像をダウンロードする

ネットから画像をダウンロードするときも同じことが起こります。いくつかのバイトは何かに変わります。私はバイトをバイトで比較しました。 文字列に変換して表示しますか?シンボルの代わりに。私は読者とバイト配列入力ストリームを試してみました。私はネット上のすべての例を試しました。私がやっている間違いは何ですか?

更新(答えは受け入れ):

あなたが送信または受信オブジェクトのMIMEを確認してください。バイナリファイルの場合は、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

... –

答えて

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 –

0

私はソケットクライアントサーバーアプリケーションを構築していたときも同様の問題がありました。バイトは奇妙な文字で、私はそれらを試して比較するためにあらゆる種類のことを試しました。それから、some1が私にdatainputstream、dataoutstreamを使用し、バイトとの変換を行わせるべきであると私が指摘した議論を見つけました。それは私のために完全に働いた。私は決して全くバイトに触れなかった。

関連する問題