赞
踩
1、编程实现一个类“MyFSDataInputStream”,该类继承“org.apache.hadoop.fs.FSDataInputStream”,要求如下:实现按行读取HDFS中指定文件的方法“readLine()”,如果读到文件末尾,则返回空,否则返回文件一行的文本。
2、查看Java帮助手册或其它资料,用”java.net.URL”和“org.apache.hadoop.fs.FsURLStreamHandler
Factory”编程完成输出HDFS中指定文件的文本到终端中。
1、
package Second; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; public class MyFsDataInputStream extends FSDataInputStream{ public MyFsDataInputStream(InputStream in) { super(in); } public static String readline(Configuration conf,String filename) throws IOException { Path filename1=new Path(filename); FileSystem fs=FileSystem.get(conf); FSDataInputStream in=fs.open(filename1); BufferedReader d=new BufferedReader(new InputStreamReader(in)); String line=d.readLine(); if (line!=null) { d.close(); in.close(); return line; }else return null; } public static void main(String[] args) throws IOException { Configuration conf=new Configuration(); conf.set("fs.defaultFS", "hdfs://localhost:9000"); conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem"); FileSystem fs=FileSystem.get(conf); String filename="/user/hadoop/myLocalFile.txt"; System.out.println("读取文件:"+filename); String o=MyFsDataInputStream.readline(conf, filename); System.out.println(o+"\n"+"读取完成"); } }
2、
package Second; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import org.apache.hadoop.fs.FsUrlStreamHandlerFactory; import org.apache.hadoop.io.IOUtils; public class FSUrl { static { URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory()); } public static void cat(String filename) throws MalformedURLException, IOException { InputStream in=new URL("hdfs","localhost",9000,filename).openStream(); IOUtils.copyBytes(in, System.out,4096,false); IOUtils.closeStream(in); } public static void main(String[] args) throws MalformedURLException, IOException { String filename="/user/hadoop/myLocalFile.txt"; System.out.println("读取文件"+filename); FSUrl.cat(filename+"\n读取完成"); } }
(1)、启动浏览器查看Namenode、Datanode节点信息以及文件信息(hadoop3.0以上访问的是9870,而3.0以下则是50070)
注意需要先在终端中启动hadoop
(2)、从浏览器中查看文件的内容
(3)、运行eclipse代码结果
(1)、查看文件的内容
(2)、运行eclipse中代码的结果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。