大数据 实验一:大数据系统基本实验 熟悉常用的HDFS操作_大数据系统及应用-hdfs实训(3)

2)熟练使用 HDFS 操作常用的 shell 命令。

3)熟悉 HDFS 操作常用的 Java API。

📚实验平台

1)操作系统:Linux;

2)Hadoop 版本:3.2.2;

3)JDK 版本:1.8;

4)Java IDE:Eclipse。

📚实验内容

编程实现以下功能,并利用 Hadoop 提供的 Shell 命令完成相同任务

⭐️HDFSApi

1)向 HDFS 中上传任意文本文件。如果指定的文件在 HDFS 中已经存在,则由用户来指定是追加到原有文件末尾还是覆盖原有的文件;

Shell命令

检查文件是否存在,可以使用如下命令:

cd /usr/local/hadoop
./bin/hdfs dfs -test -e text.txt
#执行完上述命令不会输出结果,需要继续输入以下命令查看结果
echo $?

重启了虚拟机开始做这个实验,一开始出现报错,搜索后发现原来是hadoop没开

在这里插入图片描述

在这里插入图片描述


在这里插入图片描述

echo $? 返回上一个命令的状态,0表示没有错误,其他任何值表明有错误(这里显然出错,因为还没有建text.txt文件夹),手动建一个text.txt然后拖到/usr/local/hadoop。

在这里插入图片描述

在这里插入图片描述


用户可以选择追加到原来文件末尾或者覆盖原来文件

cd /usr/local/hadoop
./bin/hdfs dfs -appendToFile local.txt text.txt #追加到原文件末尾
#touch local.txt
./bin/hdfs dfs -copyFromLocal -f local.txt text.txt #覆盖原来文件,第一种命令形式
./bin/hdfs dfs -cp -f file:///usr/local/hadoop/local.txt text.txt#覆盖原来文件,第二种命令形式

在这里插入图片描述

这样会自动建一个local.txt文件

在这里插入图片描述

在这里插入图片描述

实际上,也可以不用上述方法,而是采用如下命令来实现

if $(hdfs dfs -test -e text.txt);
then $(hdfs dfs -appendToFile local.txt text.txt);
else $(hdfs dfs -copyFromLocal -f local.txt text.txt);
fi

在这里插入图片描述


编程实现

在这里插入图片描述

package HDFSApi;
import java.util.Scanner;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.\*;
import java.io.\*; 
public class HDFSApi 
{ 
    /\*
 判断路径是否存在
 \*/
    public static boolean test(Configuration conf, String path) throws IOException 
    {         
        FileSystem fs = FileSystem.get(conf);       
        return fs.exists(new Path(path)); 
    } 
    /\*
 复制文件到指定路径
 若路径已存在,则进行覆盖
 \*/
    public static void copyFromLocalFile(Configuration conf, String localFilePath, String remoteFilePath) throws IOException 
    { 
        FileSystem fs = FileSystem.get(conf); 
        Path localPath = new Path(localFilePath); 
        Path remotePath = new Path(remoteFilePath); 
        /\* fs.copyFromLocalFile 第一个参数表示是否删除源文件,第二个参数表示是否覆盖 \*/
        fs.copyFromLocalFile(false, true, localPath, remotePath);      
        fs.close(); 
    } 
    /\*
 追加文件内容
 \*/
    public static void appendToFile(Configuration conf, String  localFilePath, String remoteFilePath) throws IOException 
    { 
        FileSystem fs = FileSystem.get(conf); 
    
  • 12
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值