项目中需要把消息写到hdfs文件系统中去,所以看了一下如何通过java来操作hdfs文件,这里记录一下.
不过效果不是很满意.需要优化的地方还很多,希望博客大神能指导一下.
下面是基本操作工具类
package testHbase2.common.util;
import java.io.IOException;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
/**
* 操作hdfs文件工具
*
* @author yhy
*
*/
public class HDFSUtils {
public static void appendHDFS(String hdfs, String data) {
Configuration conf = new Configuration();
conf.setBoolean("dfs.support.append", true);//有说法是添加了这个属性,就能再hdfs问价后面追加,但没有实现.
FileSystem fs;
try {
fs = FileSystem.get(URI.create(hdfs), conf);
Path path = new Path(hdfs);
if(!fs.exists(path)){//判断文件是否存在
FSDataOutputStream out = fs.create(path);
out.write(data.getBytes("UTF-8"));
out.close();
}else{//看网上说了很多hdfs文件最好不要追加操作,能理解缘由,但没有想到更好的办法来实现业务需求,所以用了一个很笨的办法.就是先读取,再写入,但好像有点问题.
FSDataInputStream in = fs.open(path);
byte[] ioBuffer = new byte[10240];
int readLen = in.read(ioBuffer);
while (readLen != -1) {
readLen = in.read(ioBuffer);
}
in.close();
String str = new String(ioBuffer) + "\r\n"+data;
FSDataOutputStream out = fs.create(path);
out.write(str.getBytes("UTF-8"));
out.close();
}
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
下面是调用main方法
package testHbase2.controller;
import testHbase2.common.util.HDFSUtils;
public class WsController {
public static void main(String[] args) {//这里的9000端口是可以在hadoop安装环境下的配置文件hdfs-site.xml中配置的.(好像是这个文件.不是的话百度一下就出来了,很简单)
HDFSUtils.appendHDFS("hdfs://192.168.32.128:9000/usr/local/hadoop/t.txt", "测试数据222");
}
}