云计算-HDFS接口编程

调用HDFS文件接口实现对分布式文件系统中文件的访问,如创建、修改、删除等。

开启与关闭

public class HdfsTest {
	
  private FileSystem fs;

  @Before
  public void init() throws URISyntaxException, IOException, InterruptedException {
    Configuration configuration = new Configuration();
    URI uri = new URI("hdfs://192.168.10.130:8020");
    fs = FileSystem.get(uri, configuration, "root");
  }

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

新建一个文件夹

/**
* 创建一个文件夹
*/
@Test
public void mkdir() {
  try {
    fs.mkdirs(new Path("/hdfs_study"));
  } catch (IOException e) {
    e.printStackTrace();
  }
}

创建文件

/**
* 创建文件
*/
@Test
public void detail() throws IOException {
  FSDataOutputStream os = fs.create(new Path("hdfs://192.168.10.130:8020/hdfs_study/word.txt"));
  String string = "Hello World\nMy name is Zihoo\nHello Hadoop";
  byte[] buff = string.getBytes(StandardCharsets.UTF_8);
  os.write(buff, 0, buff.length);
}

向终端展示文件内容

//向终端展示文件内容
@Test
public void showFile() throws InterruptedException, IOException, URISyntaxException {
  FSDataInputStream in = fs.open(new Path("hdfs://192.168.10.130:8020/hdfs_study/word.txt"));
  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
  String content =  bufferedReader.readLine(); //读取文件一行
  while (content!=null){
    System.out.println(content);
    content=bufferedReader.readLine();
  }
  bufferedReader.close();
  in.close();
}

向文件追加内容

//向已有文件追加内容
@Test
public void appendFile() throws IOException, URISyntaxException, InterruptedException {
  String content = "这是一段追加的内容";
  FSDataOutputStream out = fs.append(new Path("hdfs://192.168.10.130:8020/hdfs_study/word.txt"));
  out.write(content.getBytes());  //默认追加在末尾
  IOUtils.closeStream(out);
}

文件上传

/**
* 上传文件
*/
@Test
public void put() {
  /**
  * delSrc: Boolean  上传后是否删除源文件
  * overwrite: Boolean   是否允许覆盖
  * src: Path    源数据路径
  * dst: Path    目的地路径
  */
  try {
    fs.copyFromLocalFile(false, false, new Path("F:\\桌面\\教材电子版\\大数据\\MapReduce实验资料\\word.txt"), new Path("hdfs://192.168.10.130:8020/hdfs_study"));
  } catch (IOException e) {
    e.printStackTrace();
  }
}

下载文件

@Test
public void get() throws IOException {
  /**
  * delSrc: Boolean  上传后是否删除源文件
  * src: Path    源数据路径
  * dst: Path    目的地路径
  * useRawLocalFileSystem    是否开启本地校验
  */
  fs.copyToLocalFile(false, new Path("hdfs://192.168.10.130:8020/hdfs_study/word.txt"), new Path("E:\\hdfs_study\\word.txt"), true);
}

文件的更名和移动

@Test
public void move() throws IOException {
  /**
  * Path:源文件路径
  * Path:目标文件路径
  */

  // 将/hdfs_study/word.txt移动并更名   /word_rename.txt
  fs.rename(new Path("hdfs://192.168.10.130:8020/hdfs_study/word.txt"), new Path("hdfs://192.168.10.130:8020/word_rename.txt"));
}

文件删除

@Test
public void remove() throws IOException {
  fs.delete(new Path("hdfs://192.168.10.130:8020/word_rename.txt"), true);
}
posted @ 2021-11-26 18:52  Gazikel  阅读(227)  评论(0)    收藏  举报