2016-08-10 8 views
-1

私の目標は、別のファイルからファイルの内容を削除することです。これらのファイルはHttpURLConnectionを介してアクセスできます。入力ストリームの最後からNバイトを削除します

私の考えは、最初のファイルからコンテンツの長さを取得することです。このコンテンツの長さをNとしましょう。また、2番目の入力ストリーム(file2)Nバイトから削除します。

HttpURLConnection connection1 = (HttpURLConnection) url1.openConnection(); 
HttpURLConnection connection2 = (HttpURLConnection) url2.openConnection(); 

String contentLength1 = connection1.getHeaderFields().get("Content-Length").get(0); 
String contentLength2 = connection2.getHeaderFields().get("Content-Length").get(0); 
InputStream is = connection2.getInputStream(); 

EDIT:

私はより良い方法があるかどうか、私は疑問に思う、それを行うための方法を発見しました。

ByteArrayOutputStream into = new ByteArrayOutputStream(); 
byte[] buf = new byte[4096]; 

for (int n; 0 < (n = is.read(buf));) { 
    into.write(buf, 0, n); 
} 
into.close(); 

byte[] data = into.toByteArray(); 
int length1 = Integer.parseInt(contentLength1); 
int length2 = Integer.parseInt(contentLength2); 
byte[] newData = new byte[length2-length1]; 

System.arraycopy(data, 0, newData, 0, newData.length); 
ByteArrayInputStream newStream = new ByteArrayInputStream(newData); 
+1

プラットフォームにタグを付けてください。質問が広すぎる限り、あなたが試したことを示してください。http://stackoverflow.com/help/how-to-ask – EJoshuaS

+0

@Yassine Javaでコーディングしていますか?これは私が知っている唯一の一般的な言語で、標準ライブラリの一部として 'HttpURLConnection'クラスを持っています。関連するコードを提示してください。 – callyalater

+0

私の質問を編集して、私の問題についての詳細な情報を提供しました – Yassine

答えて

0

あなたの入力ストリームを、目的の長さだけ読み上げるクラスにラップします。

class TruncatedInputStream extends InputStream { 

    private final InputStream in; 
    private final long maxLength; 
    private long position; 

    TruncatedInputStream(InputStream in, long maxLength) ... { 
     this.in = in; 
     this.maxLength = maxLength; 
    } 

    @Override 
    int read() ... { 
     if (position >= maxLength) { 
      return -1; 
     } 
     int ch = in.read(); 
     if (ch != -1) { 
      ++position; 
     } 
     return -1; 
    } 
} 

マインドスキップ、リセット。 BufferedInputStreamの使用法はお勧めできません。

これはもう少しタイピングしていますが、実際には1つの責任を持つ実力のあるツールです。

関連する問題