publicclassFIleSystemCat {/***@paramargs
*@throwsIOException*/static{//这句是为了让程序识别hdfs协议而进行的设置//setURLStreamHandlerFactory:设置url流处理器工厂URL.setURLStreamHandlerFactory(newFsUrlStreamHandlerFactory());
}publicstaticvoidmain(String[] args)throwsIOException {//TODO Auto-generated method stubString path1="hdfs://localhost:9000/user/hadoop/photo/DSC01283.JPG";
String path2="/home/hadoop/qiu.jpg";
InputStream in=null;
OutputStream out=null;
in=newURL(path1).openStream();
out=newFileOutputStream(path2);
IOUtils.copyBytes(in, out,4096,false);
}
}在某些情况下设置URLStreamHandlerFactory的方式并不一定回生效。在这种情况下,需要用FileSystem API来打开一个文件的输入流。
文件的位置是使用Hadoop Path呈现在Hadoop中的,与java.io中的不一样。
有两种方式获取FileSystem的实例:
public static FileSystem get(Configuration conf) throws IOException
public static FileSystem get(URI uri, Configuration conf) throws IOException
Configuration封装了client或者server的配置,这些配置从classpath中读取,比如被classpath指向的conf/core-site.xml文件.
第一个方法从默认位置(conf/core-site.xml)读取配置,第二个方法根据传入的uri查找适合的配置文件,若找不到则返回使用第一个方法,即从默认位置读取。
在获得FileSystem实例之后,我们可以调用open()方法来打开输入流:
public FSDataInputStream open(Path f) throws IOException
public abstract FSDataInputStream open(Path f, int bufferSize) throws IOException
第一个方法的参数f是文件位置,第二个方法的bufferSize就是输入流的缓冲大小。
下面的代码是使用FileSystem打开输入流的示例:
本文介绍了如何使用Java的FileSystem API将HDFS上的文件复制到本地文件系统。通过设置URLStreamHandlerFactory,然后利用FileSystem的open()方法打开文件输入流,并通过IOUtils进行数据复制。此外,还解释了Configuration对象的作用以及FileSystem实例的获取方法。
1675

被折叠的 条评论
为什么被折叠?



