我有一项任务。在http服务器上传一部分文件(我必须跳过文件的开头)。
我该怎么办?你知道好的解决方案吗?
我可以使用自己的解决方案吗?这样安全吗?
我的解决方案。我创建了FileEntity的子类,它提供文件流并跳过文件的开头。
我把我的实体请求。
HttpPut request = new HttpPut(this.uri);
request.setEntity(new FileOfsetEntity(new File(getDestination()),“binary / octet-stream”,ofset));
我的FileOfsetEntity会跳过文件的开头。
class FileOfsetEntity extends FileEntity {
long ofset = 0;
public FileOfsetEntity(File file, String contentType, long ofset) {
super(file, contentType);
this.ofset = ofset;
}
@Override
public long getContentLength() {
return this.file.length() - ofset;
}
@Override
public InputStream getContent() throws IOException {
FileInputStream in = new FileInputStream(this.file);
long skiped = in.skip(ofset);
Log.w("FileOfsetEntity.getContent","skiped = " + skiped);
return in;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream instream = new FileInputStream(this.file);
long skiped = instream.skip(ofset);
Log.w("FileOfsetEntity.writeTo","skiped = " + skiped);
try {
byte[] tmp = new byte[4096];
int l;
long readed = skiped;
while ((l = instream.read(tmp)) != -1) {
readed += l;
outstream.write(tmp, 0, l);
Log.v("FileOfsetEntity.writeTo",file.getAbsolutePath() + " readed = " + readed + " skiped = " + skiped);
}
outstream.flush();
} finally {
instream.close();
} }}
答案 0 :(得分:1)