一、实验目的
(1)理解HDFS在Hadoop体系结构中的角色。 (2)熟练使用HDFS操作常用的Shell命令。 (3)熟悉HDFS操作常用的Java API。
二、实验平台
操作系统:Linux。 Hadoop 版本:2.7.3 或以上版本。 JDK 版本:1.7 或以上版本。 Java IDE:IDEA
三、实验内容和要求
(1)编程实现以下指定功能,并利用 Hadopp 提供的 Shell 命令完成相同的任务。
1. 向HDFS中上传任意文本文件,如果指定的文件在 HDFS 中已经存在,由用户指定是追加到原有文件末尾还是覆盖原有的文件。
shell:
hadoop fs -put /User/Binguner/Desktop/test.txt /test
hadoop fs -appendToFile /User/Binguner/Desktop/test.txt /test/test.txt
hadoop fs -copyFromLocal -f /User/Binguner/Desktop/test.txt / input/test.txt
复制代码
/**
* @param fileSystem
* @param srcPath 本地文件地址
* @param desPath 目标文件地址
*/
private static void test1(FileSystem fileSystem,Path srcPath, Path desPath){
try {
if (fileSystem.exists(new Path("/test/test.txt"))){
System.out.println("Do you want to overwrite the existed file? ( y / n )");
if (new Scanner(System.in).next().equals("y")){
fileSystem.copyFromLocalFile(false,true,srcPath,desPath);
}else {
FileInputStream inputStream = new FileInputStream(srcPath.toString());
FSDataOutputStream outputStream = fileSystem.append(new Path("/test/test.txt"));
byte[] bytes = new byte[1024];
int read = -1;
while ((read = inputStream.read(bytes)) > 0){
outputStream.write(bytes,0,read);
}
inputStream.close();
outputStream.close();
}
}else {
fileSystem.copyFromLocalFile(srcPath,desPath);
}
} catch (IOException e) {
e.printStackTrace();
}
}
复制代码
运行结果:
HDFS 中原来到文件列表:
第一次运行:
HDFS 中文件列表:
第二次运行:
此时 HDFS 中的目录:
2. 从HDFS中下载指定文件,如果本地文件与要下载的文件名称相同,则自动对下载的文件重命名。
shell:
hadoop fs -copyToLocal /input/test.txt /User/binguner/Desktop/test.txt
复制代码
/**
* @param fileSystem
* @param remotePath HDFS 中文件的地址
* @param localPath 本地要保存的文件的地址
*/
private static void test2(FileSystem fileSystem,Path remotePath, Path localPath){
try {
if (fileSystem.exists(remotePath)){
fileSystem.copyToLocalFile(remotePath,localPath);
}else {
System.out.println("Can't find this file in HDFS!");
}
} catch (FileAlreadyExistsException e){
try {
System.out.println(localPath.toString());
fileSystem.copyToLocalFile(remotePath,new Path("src/test"+ new Random().nextInt()+".txt"));
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
复制代码
执行前本地目录:
第一次执行:
第二次执行: