- 如果數(shù)據(jù)存放在hdfs上肢预,一次性需要讀取多個(gè)則需要批量讀取读存,可以使用下面代碼,先獲取到路徑下的所有文件名航攒,再循環(huán)讀取磺陡。
Configuration conf=new Configuration();
FileSystem hdfs=FileSystem.get(conf);
//這里的路徑是在hdfs上的存放路徑,但是事先需將hdfs-site.xml文件放在工程的source文件下漠畜,這樣才能找到hdfs
Path path=new Path("user/my/testData/201912/");
FileStatus[] stats=hdfs.listStatus(path);
for (int i=0; i<stats.length; i++){
//打印每個(gè)文件路徑
System.out.println(stats[i].getPath().toString());
//讀取每個(gè)文件
InputStream inputStream=hdfs.open(stats[i].getPath());
InputStreamReader inputStreamReader= new InputStreamReader(inputStream);
BufferedReader reader=new BufferedReader(inputStreamReader);
String line="";
while((line=reader.readLine())!=null){
System.out.println(line);
//可以在這里對(duì)每一條數(shù)據(jù)進(jìn)行處理
}
}
- 如果需要使用通配符币他,匹配得到多個(gè)文件路徑或者多個(gè)文件夾下面的多個(gè)文件路徑,需要修改上面代碼中的兩行
//匹配得到某個(gè)文件夾下所有文件路徑
Path path=new Path("user/my/testData/201912/*");
FileStatus[] stats=hdfs.globStatus(path);
//匹配得到符合某個(gè)條件下的所有文件夾下的文件路徑
//例如匹配文件夾名以2019開頭的目錄下所有文件
Path path=new Path("user/my/testData/2019*/*");
FileStatus[] stats=hdfs.globStatus(path);
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者