Des exemples d'opérations d'opération de fichiers HDFS, y compris le téléchargement de fichiers sur HDFS, le téléchargement de fichiers à partir de HDFS et la suppression de fichiers sur HDFS.
La copie de code est la suivante:
import org.apache.hadoop.conf.configuration;
import org.apache.hadoop.fs. *;
Importer java.io.file;
Importer java.io.ioException;
classe publique hadoopfile {
configuration privée conf = null;
public hadoopfile () {
conf = nouvelle configuration ();
conf.AddreSource (nouveau chemin ("/ hadoop / etc / hadoop / core-site.xml"));
}
public hadoopfile (configuration conf) {
this.conf = conf;
}
public boolean sendFile (String Path, String localfile) {
Fichier fichier = nouveau fichier (localfile);
if (! file.isfile ()) {
System.out.println (file.getName ());
retourne false;
}
essayer {
FileSystem localfs = filesystem.getLocal (conf);
FileSystem hadoopfs = filesystem.get (conf);
Path hadpath = nouveau chemin (chemin);
FsdataOutputStream fsout = hadoopfs.create (new Path (path + "/" + file.getName ()));
FsdatainputStream fsin = localfs.open (nouveau chemin (localfile));
octet [] buf = nouveau octet [1024];
int readBytes = 0;
while ((readBytes = fsin.read (buf))> 0) {
fsout.write (buf, 0, readBytes);
}
fsin.close ();
fsout.close ();
Filestatus [] hadfiles = hadoopfs.liststatus (hadpath);
pour (Fistatus fs: hadfiles) {
System.out.println (fs.toString ());
}
Retour Vrai;
} catch (ioexception e) {
e.printStackTrace ();
}
retourne false;
}
Delfile booléen public (String Hadfile) {
essayer {
FileSystem hadoopfs = filesystem.get (conf);
PATH HADPATH = NOUVEAU PATH (HADFILE);
Path p = hadpath.getparent ();
booléen rtnval = hadoopfs.delete (hadpath, true);
Filestatus [] hadfiles = hadoopfs.liststatus (p);
pour (Fistatus fs: hadfiles) {
System.out.println (fs.toString ());
}
retour rtnval;
} catch (ioexception e) {
e.printStackTrace ();
}
retourne false;
}
public boolean downloadfile (String hadfile, string localpath) {
essayer {
FileSystem localfs = filesystem.getLocal (conf);
FileSystem hadoopfs = filesystem.get (conf);
PATH HADPATH = NOUVEAU PATH (HADFILE);
FsdataOutputStream fsout = localfs.create (new Path (localPath + "/" + hadpath.getName ()));
FsdatainputStream fsin = hadoopfs.open (hadpath);
octet [] buf = nouveau octet [1024];
int readBytes = 0;
while ((readBytes = fsin.read (buf))> 0) {
fsout.write (buf, 0, readBytes);
}
fsin.close ();
fsout.close ();
Retour Vrai;
} catch (ioexception e) {
e.printStackTrace ();
}
retourne false;
}
}