View Javadoc
1   package com.foxinmy.weixin4j.http.entity;
2   
3   import java.io.File;
4   import java.io.FileInputStream;
5   import java.io.IOException;
6   import java.io.InputStream;
7   import java.io.OutputStream;
8   
9   import com.foxinmy.weixin4j.http.ContentType;
10  
11  public class FileEntity implements HttpEntity {
12  
13  	private final File file;
14  	private final ContentType contentType;
15  
16  	public FileEntity(File file) {
17  		this(file, ContentType.DEFAULT_BINARY);
18  	}
19  
20  	public FileEntity(File file, ContentType contentType) {
21  		this.file = file;
22  		this.contentType = contentType;
23  	}
24  
25  	@Override
26  	public ContentType getContentType() {
27  		return contentType;
28  	}
29  
30  	@Override
31  	public long getContentLength() {
32  		return this.file.length();
33  	}
34  
35  	@Override
36  	public InputStream getContent() throws IOException {
37  		return new FileInputStream(this.file);
38  	}
39  
40  	@Override
41  	public void writeTo(OutputStream outstream) throws IOException {
42  		InputStream instream = new FileInputStream(this.file);
43  		try {
44  			byte[] tmp = new byte[4096];
45  			int l;
46  			while ((l = instream.read(tmp)) != -1) {
47  				outstream.write(tmp, 0, l);
48  			}
49  			outstream.flush();
50  		} finally {
51  			instream.close();
52  		}
53  	}
54  }