1. download files to Local
public class Hdfsurltest {
static{
register URL let java program identify the url of HDFs
Url.seturlstreamhandlerfactory (New Fsurlstreamhandlerfactory ());
}
public static void Main (string[] args) {
InputStream in = null;
OutputStream out = null;
try {
String file = "Hdfs://hadoop-yarn.test.com:8020/user/testi/conf/core-site.xml";
URL fileUrl = new URL (file);
in = Fileurl.openstream ();
out = new FileOutputStream (New File ("D:/core-site.xml"));
Download files to local
Ioutils.copybytes (in,out,4096, false);
} catch (Exception e) {
E.printstacktrace ();
}finally{
Ioutils.closestream (in);}}
2. View cluster information
public static void Cluserstatus () throws exception{
FileSystem fs = Hdfsutil.getfs ();
Distributedfilesystem DFS = (distributedfilesystem) fs;
Fsstatus FSS = Dfs.getstatus ();
datanodeinfo[] Datanodeinfos = Dfs.getdatanodestats ();
for (Datanodeinfo Datanodeinfo:datanodeinfos) {
System.out.println (Datanodeinfo.gethostname ());}}
3. Create a Folder
public void Testhdfsmkdir () throws exception{
String Hdfsurl = "hdfs://192.168.10.11:8020";
Configuration conf= new configuration ();
FileSystem fs = Filesystem.get (Uri.create (Hdfsurl), conf);
Path PATH = new Path ("/bigdata");
Fs.mkdirs (path);}
4. Create a file
public void Testcreatefile () throws exception{
String Hdfsurl = "hdfs://192.168.10.11:8020";
Configuration conf= new configuration ();
FileSystem fs = Filesystem.get (Uri.create (Hdfsurl), conf);
Path PATH = new Path ("/bigdata/a.txt");
Fsdataoutputstream out = fs.create (path);
Out.write ("Hello Hadoop". getBytes ());}
5. File renaming
public void Testrenamefile () throws exception{
String Hdfsurl = "hdfs://192.168.10.11:8020";
Configuration conf= new configuration ();
FileSystem fs = Filesystem.get (Uri.create (Hdfsurl), conf);
Path PATH = new Path ("/bigdata/a.txt");
Path NewPath = new Path ("/bigdata/b.txt");
System.out.println (Fs.rename (path, NewPath));}
6. Uploading Files
public static void Write () throws exception{
FileSystem fs = Hdfsutil.getfs ();
OutputStream OutStream = fs.create (New Path ("/user/lcc/conf/put-core-site.xml"));
FileInputStream instream = new FileInputStream (New File ("D:/core-site.xml"));
Ioutils.copybytes (instream, OutStream, 4096, true);}
The easiest way for Hadoop programs to read data in HDFs is to open a data stream with a Java URL object and read from it data .
A fsurlstreamhandlerfactory instance is required to invoke a URL set over , This method A Java virtual machine can only be called once , and the downside is that if the rest of the program is set up, it can no longer read data from Hadoop.
New method that requires the input stream of a file to be opened using the filesystem API .
Files are treated as a Hadoop path object in the Hadoop file system , and a folder or file path is viewed as a URL to a hadoop file System .
Three different methods.
Get(conf) and get(URI,conf), newinstance
HDFs Common API (Java)