Environment: Eclipse + Eclipse Hadoop plugin, Hadoop + rhel6.4
Package Test;import Java.io.ioexception;import Java.net.uri;import org.apache.hadoop.conf.configuration;import Org.apache.hadoop.fs.filesystem;import Org.apache.hadoop.fs.Path; Import Org.apache.hadoop.fs.fsdatainputstream;import org.apache.hadoop.fs.FSDataOutputStream;; public class Test {public void WriteFile (String HDFs) throws IOException {Configuration conf = new configuration (); FileSystem fs = Filesystem.get (Uri.create (HDFS), conf); Fsdataoutputstream Hdfsoutstream = fs.create (new Path (HDFs)); Hdfsoutstream.writechars ("Hello"); hdfsoutstream.close (); Fs.close ();} public void ReadFile (String HDFs) throws IOException {configuration conf = new Configuration (); FileSystem fs = Filesystem.get (Uri.create (HDFS), conf); Fsdatainputstream Hdfsinstream = Fs.open (new Path (HDFs)), byte[] Iobuffer = new Byte[1024];int Readlen = Hdfsinstream.read (Iobuffer); while (Readlen!=-1) {System.out.write (iobuffer, 0, readlen); Readlen = Hdfsinstream.read (Iobuffer);} Hdfsinstream.close (); Fs.close ();} public static void MAin (string[] args) throws IOException {String HDFs = "Hdfs://192.168.56.112:9000/test/hello.txt"; Test T = new test (); T.writefile (HDFs); T.readfile (HDFS); }}
Java read and write HDFs simple demo