2016-08-10 2 views
-1

내 목표는 다른 파일에서 파일의 내용을 삭제하는 것이며, HttpURLConnection을 통해 해당 파일에 액세스 할 수 있습니다.입력 스트림의 끝에서 N 바이트를 삭제하십시오.

제 아이디어는 첫 번째 파일에서 content-length를 얻는 것입니다. N을 this content-length라고 부릅니다. 그리고 두 번째 입력 스트림 (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(); 

편집 :

나는 더 나은 방법이 있는지 궁금, 그것을 할 수있는 방법을 발견했다.

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 자바로 코딩 하시겠습니까? 표준 라이브러리의 일부로'HttpURLConnection' 클래스를 가지고있는 유일한 대중 언어입니다. 도움이되는 관련 코드를 제시하십시오. – callyalater

+0

내 문제에 대한 추가 정보를 제공하기 위해 내 질문을 편집했습니다. – Yassine

답변

0

원하는 길이까지 읽는 클래스로 InputStream을 래핑하십시오.

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의 사용은 권유 할 수 없습니다.

실제로는 좀 더 타이핑하는 것이지만 단 하나의 책임을 지닌 견고한 도구를 제공합니다.