HDFS读写文件的java代码

本文介绍了如何使用Java代码进行HDFS文件的读取和写入操作,包括通过URL和FileSystem类的方式读文件,以及如何将本地文件复制到HDFS。此外,还展示了获取HDFS目录中文件的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对HDFS操作可以通过命令行,-put,-mkdir,-rm等等,也可以通过java代码来实现,

总结一下读写的两个操作,其他的功能可以通过FileSystem类的方法获取。


HDFS读文件的操作:

可以通过简单的URL读取,也可以通过FileSystem读取,代码如下:


//通过URL读取

public class URLText {
static{
URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
}

public static void main(String[] a) throws Exception{
InputStream in = null;
try{
in = new URL(a[0]).openStream();
//参1输入流,参2,输出流,参3缓存字节,参4是否设置自动关闭输入输出流
IOUtils.copyBytes(in, System.out, 4096, false);
}finally{
IOUtils.closeStream(in);
}
}
}


//通过FileSystem读取

public class FileSystemText {
public static void main(String[] args) throws Exception {
String url = args[0];
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(URI.create(url), configuration);
InputStream in = null;
try{
in = fs.open(new Path(url));
IOUtils.copyBytes(in, System.out, configuration, false);
}finally{
IOUtils.closeStream(in);
}
}
}




HDFS写文件的操作:

public class CopyFile {
public static void main(String[] a) throws Exception {
String localurl = a[0];//本地文件地址
String hdfsurl = a[1];//输出流在hdfs里存放文件地址
Configuration configuration = new Configuration();
InputStream inputStream 

= new BufferedInputStream(new FileInputStream(localurl));

FileSystem fs = FileSystem.get(URI.create(hdfsurl), configuration);
// OutputStream outputStream = fs.create(new Path(hdfsurl));
OutputStream outputStream = fs.append(new Path(hdfsurl));

IOUtils.copyBytes(inputStream, outputStream, configuration, true);
}
}



获取HDFS文件目录的操作:

public class FileListCat {
public static void main(String[] a) throws Exception {
String url = a[0];

Path[] p = new Path[a.length];
for (int i = 0; i < a.length; i++) {
p[i] = new Path(a[i]);
}

Configuration configuration = new Configuration();

FileSystem fs = FileSystem.get(URI.create(url), configuration);
FileStatus[] listStatus = fs.listStatus(p);
/*      for (FileStatus fileStatus : listStatus) {
System.out.println(fileStatus.getPath());
}        */
Path[] stat2Paths = FileUtil.stat2Paths(listStatus);
for (Path path : stat2Paths) {
System.out.println(path);
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值