Hadoop Learning Note 0003--reading data from a Hadoop URL
from Hadoopurl reading Data
to from Hadoop The simplest way to read files in a file system is to use the Java.net.URL object to open a data stream from which to read the data. The general format is as follows:
InputStream in = null; try {in = new URL ("Hdfs://host/path"). OpenStream (); Process in } finally { ioutils.closestream (in); } <span style= "Font-weight:bold;" ></span>
a little work is needed here to get JavaIdentifyHadoopof the file systemURLsolution is to pass afsurlstreamhandlerfactoryinstance to invoke theURLin theseturlstreamhandler-factorymethod. This method in aJavaThe virtual machine can only be called once, so it is generally executed in a static block. This limitation means that if other parts of the program(It could be a third-party part that's not in your control.)set aurlstreamhandlerfactory, we will no longer be able toHadoopTo read the data.
public class Urlcat { static { url.seturlstreamhandlerfactory (new Fsurlstreamhandlerfactory ()); } public static void Main (string[] args) throws Exception { inputstream in = null; try {in = new URL (Args[0]). OpenStream (); Ioutils.copybytes (in, System.out, 4096, false); } finally { ioutils.closestream (in);}} }
We use Hadoop in a concise ioutils class in finally clause to close the data stream while copying the bytes between the input stream and the output stream ( In this case , System.out) . The last two parameters of the Copybytes method, which is the size of the buffer to be copied, which indicates whether the data flow is closed after the copy has ended. Here, the input stream is switched off, and the system.out does not need to be closed.
The instance operations are as follows:
1 , create a new map/reduce Project Project
2 , establish a Urlcat class, package name com.hadoop.test
Package Com.hadoop.test;import Java.io.inputstream;import Java.net.url;import Org.apache.hadoop.fs.fsurlstreamhandlerfactory;import Org.apache.hadoop.io.ioutils;public class URLCat { static { url.seturlstreamhandlerfactory (new Fsurlstreamhandlerfactory ()); } public static void Main (string[] args) throws Exception { inputstream in = null; try {in = new URL (Args[0]). OpenStream (); Ioutils.copybytes (in, System.out, 4096, false); } finally { ioutils.closestream (in); } }
3 , Test
in the Urlcat Interface Right click Select Run As->run Configurations
4. Test results
Hadoop Learning Note 0003--reading data from a Hadoop URL