Hadoop-部分测试API

本文详细介绍了一个使用Java进行HDFS操作的实例,包括文件上传、下载、删除及展示目录内容等功能,通过JUnit测试框架验证了HDFS操作的正确性和效率。

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

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.*;

import static org.junit.Assert.*;
public class TestHDFS {
   private FileSystem fileSystem;
   private Configuration configuration;

   @Before
    public void before() throws IOException {
       configuration = new Configuration();
       configuration.set("fs.defaultFS","hdfs://CentOS:9000");
       configuration.set("dfs.replication","1");
       configuration.set("fs.trash.interval","1");
       fileSystem=FileSystem.get(configuration);
       assertNotNull(fileSystem);
   }

   //文件上传
   @Test
   public void testupload() throws IOException {
       InputStream inputStream = new FileInputStream("C:\\Users\\chenda\\Desktop\\wx.txt");
       Path path = new Path("xx.txt");
       OutputStream outputStream =fileSystem.create(path);
       IOUtils.copyBytes(inputStream,outputStream,1024,true);

   }

   //文件上传
   @Test
   public void testupload2() throws IOException {
       Path path = new Path("file:///C:\\Users\\chenda\\Desktop\\wx.txt");
       Path src= new Path("dd.txt");
       fileSystem.copyFromLocalFile(path,src);
   }



    //文件下载
    @Test
    public void testDownload02() throws IOException {
        OutputStream os=new FileOutputStream("C:\\Users\\chenda\\Desktop\\22.txt");
        InputStream is = fileSystem.open(new Path("dd.txt"));
        IOUtils.copyBytes(is,os,1024,true);
    }

    //删除文件
    @Test
    public void  deletetest() throws IOException {
       Path path = new Path("/dd.txt");
       fileSystem.delete(path,true);
    }

    //展示所有文件
    @Test
    public void Filelist() throws IOException {
       Path path = new Path("/");
       RemoteIterator<LocatedFileStatus> iterator=fileSystem.listFiles(path, true);
       while(iterator.hasNext()){
           LocatedFileStatus status = iterator.next();
           System.out.println(status.getPath()+" -- "+status.getLen()+"是不是文件 :"+status.isFile());
       }
    }

    @Test
    public void testDeleteWithTrash() throws IOException {
        Trash trash=new Trash(configuration);
        trash.moveToTrash(new Path("dd.txt"));
    }

   @After
   public void after() throws IOException {
       fileSystem.close();
   }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值