我是靠谱客的博主 年轻灰狼,最近开发中收集的这篇文章主要介绍使用FileSystem 进行文件上传和下载,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1、由于上一个例子、使用URL.openStream()的方式只能对文件进行下载、所以、该例子使用FileSystem

2、注意事项、请参看: hdfs 查看文件(第一个hadoop程序)

3、源码如下:该方法只实现了、简单的查询、注意设置Default URI

package org.zh.hadoop.read;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsUrlStreamHandlerFactory;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.junit.Before;
import org.junit.Test;

public class HadoopRead {
	
	@Before
	public void init() {
		URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
	}
	
	@Test
	public void read01() {
		try {
			/**
			 * A Configuration object encapsulates a client or server’s configuration, which is set using
			 * configuration files read from the classpath, such as conf/core-site.xml.
			 */
			Configuration conf = new Configuration();
			/**
			 * 此处打印出 file:/// 会默认获取到本地文件系统
			 */
			System.out.println(conf.toString());
			/**
			 * 此处会打印出默认加载的配置文件、core-site.xml /  core-default.xml
			 */
			System.out.println(conf.get("fs.default.name"));
			/**
			 * 可以通过以下各种方式设置默认的Uri 、如果不设置默认Uri 、而Configuration对象也没有获取到fs.default.name
			 * 则会抛出异常:java.lang.IllegalArgumentException: Wrong FS: hdfs://h1:9000/user/root/out/2.txt, expected: file:///
			 * if(!FileSystem.checkPath())  
			 * 	   throw new IllegalArgumentException("Wrong FS: "+path+", expected: "+this.getUri());
			 */
			conf.set("fs.default.name", "hdfs://h1:9000");
			//FileSystem.setDefaultUri(conf, "hdfs://h1:9000");
			//FileSystem fs = FileSystem.get(new URI("hdfs://h1:9000"),conf);
			/**
			 * 获取到分布式文件系统
			 */
			FileSystem fs = FileSystem.get(conf);
			InputStream is = fs.open(new Path("hdfs://h1:9000/user/root/out/2.txt"),4096);
			/**
			 * InputStream in 输入流
			 * OutputStream out 输出流
			 * int buffSize 缓冲区大小
			 * boolean close 是否关闭Stream
			 */
			IOUtils.copyBytes(is, System.out, 4096,true);
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
}



最后

以上就是年轻灰狼为你收集整理的使用FileSystem 进行文件上传和下载的全部内容,希望文章能够帮你解决使用FileSystem 进行文件上传和下载所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(61)

评论列表共有 0 条评论

立即
投稿
返回
顶部