一,依賴
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.7.3</version>
</dependency>
二,Java API
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class HDFSUtil {
public static void mkdir(Configuration conf, String path) throws IOException {
FileSystem fs = FileSystem.get(conf);
fs.mkdirs(new Path(path));
fs.close();
}
public static void delete(Configuration conf, String path) throws IOException {
FileSystem fs = FileSystem.get(conf);
fs.delete(new Path(path), true);
fs.close();
}
public static List<LocatedFileStatus> fileList(Configuration conf, String path) throws IOException {
FileSystem fs = FileSystem.get(conf);
RemoteIterator<LocatedFileStatus> iterator = fs.listFiles(new Path(path), true);
List<LocatedFileStatus> resultList = new ArrayList<>();
while (iterator.hasNext()) {
LocatedFileStatus locatedFileStatus = iterator.next();
resultList.add(locatedFileStatus);
}
fs.close();
return resultList;
}
public static List<FileStatus> fileList2(Configuration conf, String path, List<FileStatus> resultList) throws IOException {
FileSystem fs = FileSystem.get(conf);
FileStatus[] fileStatus = fs.listStatus(new Path(path));
if (resultList == null) {
resultList = new ArrayList<>();
}
for(FileStatus s : fileStatus) {
if (s.isDirectory()) {
fileList2(conf, s.getPath().toUri().getPath(), resultList);
} else {
resultList.add(s);
}
}
fs.close();
return resultList;
}
public static void upload(Configuration conf, String filePath, String hdfsPath) throws IOException {
FileSystem fs = FileSystem.get(conf);
fs.copyFromLocalFile(new Path(filePath), new Path(hdfsPath));
}
public static void download(Configuration conf, String hdfsPath, String savePath) throws IOException {
FileSystem fs = FileSystem.get(conf);
fs.copyToLocalFile(new Path(hdfsPath), new Path(savePath));
}
public static void main(String[] args) throws IOException {
System.setProperty("HADOOP_USER_NAME","root");
Configuration conf = new Configuration();
conf.set("fs.defaultFS","hdfs://10.1.255.121:9000");
conf.set("dfs.blocksize","256m");
conf.set("dfs.replication","2");
}
}