java远程读写hdfs文件内容_java读写hdfs文件

前言

最近接触了分布式文件存储系统FastDFS,但FastDFS是底层是用C语言写的,因此安装的时候还需要make,这一点很是不爽。自己之前研究过Hadoop,其中的hdfs就是一个分布式文件系统,而且Hadoop是用java语言编写的,因此考虑能否用hdfs来代替FastDFS。

经过反复实践,基本能够远程连接hdfs进行文件的操作了,直接上代码。本示例的前提是先启动hdfs文件系统,关于如何搭建hdfs文件系统请参考其他文章。

初始化

private static void init(String url) throws IOException {

Configuration config = new Configuration();

config.set("fs.defaultFS", url);

hdfs = FileSystem.get(URI.create(url), config);

}

其中url为远程hdfs地址,例如hdfs://127.0.0.1:9000

上传文件

public static void uploadFile2HDFS(String s, String d) throws IOException {

Path src = new Path(s);

Path dst = new Path(hdfs.getWorkingDirectory() + d);

hdfs.copyFromLocalFile(src, dst);

}

注:s为本地文件路径,d为远程文件保存的绝对路径,下同。

上传二进制内容,并保存成文件

public static void uploadFile2HDFS(byte[] data, String d) throws IOException {

FSDataOutputStream out = hdfs.create(new Path(hdfs.getWorkingDirectory() + d));

IOUtils.write(data, out);

out.close();

}

读取远程文件为二进制内容

public static byte[] readHDFSFile(String dst) throws Exception {

Path path = new Path(dst);

if (hdfs.exists(path)) {

FSDataInputStream is = hdfs.open(path);

FileStatus stat = hdfs.getFileStatus(path);

byte[] buffer = new byte[Integer.parseInt(String.valueOf(stat.getLen()))];

is.readFully(0, buffer);

is.close();

return buffer;

} else {

throw new Exception("the file is not found .");

}

}

删除文件或文件夹。当删除文件夹时,会同时删除子文件夹和文件。

public static boolean delete(String dst) throws IOException {

Path path = new Path(hdfs.getWorkingDirectory() + dst);

boolean isDeleted = hdfs.delete(path, true);

return isDeleted;

}

创建文件夹

public static void mkdirs(String dir) throws IOException {

System.out.println(hdfs.getWorkingDirectory() + dir);

hdfs.mkdirs(new Path(dir));

}

列出文件或文件夹(此方法未定义返回值,如有需要可自行修改)

public static void listAll(String dir) throws IOException {

FileStatus[] stats = hdfs.listStatus(new Path(hdfs.getWorkingDirectory() +dir));

for (int i = 0; i < stats.length; ++i) {

if (stats[i].isFile()) {

// regular file

System.out.println(stats[i].getPath().toString());

} else if (stats[i].isDirectory()) {

// dir

System.out.println(stats[i].getPath().toString());

} else if (stats[i].isSymlink()) {

// is s symlink in linux

System.out.println(stats[i].getPath().toString());

}

}

}

一个测试方法,仅供参考

public static void main(String[] args) throws Exception {

try {

init("hdfs://127.0.0.1:9000");

String localStr = "d:/t/pop.txt";

String dst = "/TestDirectory/hehe.txt";

uploadFile2HDFS(localStr, dst);

System.out.println("success");

hdfs.close();

} catch (Exception e) {

e.printStackTrace();

}

}

完毕。


版权声明:本文为weixin_39965673原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。