因为hbase的存储只支持文本。但当我们需要要一些文件类型上传到hbase上的时候,如果使用文件流,将它转成文本类型,上传下载是没有问题,可是这样一来,新生成的文件与原始文件的里的格式(如DOC里的图片)这样的东西就不存在了,这样的话,就没有什么意义了。
因此,上传到hbase的时候,可以通过将文件流转换成BASE64的编码,这样,上传下载仍是原文件。但是要注意的是,该文件的格式,如果格式不统一的话,还是不会出来的。
我就遇到过这样的问题,该文件是docx格式的,我下载后转成doc的,就会出问题。
下面是实现代码
public String getSource(String URL) throws IOException{ File file = new File(URL); file.length(); FileInputStream is = new FileInputStream(file); byte[] bytes = new byte[(int) file.length()]; int len=0; while( (len = is.read(bytes)) != -1 ){ is.read(bytes); } is.close(); BASE64Encoder be = new BASE64Encoder(); return be.encode(bytes); }
public String down(String tablename,String rowkey) throws IOException{ BASE64Decoder db = new BASE64Decoder(); String Content=""; HTable talbe =new HTable(tablename); Result result = null; Get get = new Get(Bytes.toBytes(Id)); get.addFamily(Bytes.toBytes("property"));//这是在hbase上存储的该文件的一些属性 get.addFamily(Bytes.toBytes("content"));//这是在hbase上存储该文件的BASE64编码的列族名 result = table.get(get); table.close(); Content = Bytes.toString(r.getValue(Bytes.toBytes("content"), Bytes .toBytes("content")));//获得到该文件的文本 String title=Bytes.toString(r.getValue(Bytes.toBytes("property"),Bytes.toBytes("title"))); String downurl=tmp+title; byte c[] = bd.decodeBuffer(tmp); FileOutputStream out = new FileOutputStream(new File(downurl)); out.write(c); out.close(); return downurl; }
这是临时写的简宜代码,有很多不足之处。