Ejemplos de operaciones de operación de archivos HDFS, incluida la carga de archivos a HDFS, descargando archivos de HDFS y eliminar archivos en HDFS.
La copia del código es la siguiente:
importar org.apache.hadoop.conf.configuration;
importar org.apache.hadoop.fs.*;
import java.io.file;
import java.io.ioException;
clase pública Hadoopfile {
Configuración privada conf = null;
public HadoopFile () {
conf = nueva configuración ();
conf.addResource (nueva ruta ("/hadoop/etc/hadoop/core-site.xml"));
}
public HadoopFile (Configuration Conf) {
this.conf = conf;
}
public boolean sendFile (string ruta, cadena localfile) {
Archivo archivo = nuevo archivo (localfile);
if (! file.isfile ()) {
System.out.println (file.getName ());
devolver falso;
}
intentar {
FileSystem localfs = filesystem.getLocal (conf);
FileSystem hadoopfs = filesystem.get (conf);
Ruta hadpath = nueva ruta (ruta);
FsDataOutputStream fSout = hadoopfs.create (nueva ruta (ruta+"/"+file.getName ()));
Fsdatainputstream fsin = localfs.open (nueva ruta (localfile));
byte [] buf = nuevo byte [1024];
int readbytes = 0;
while ((readbytes = fsin.read (buf))> 0) {
fSout.Write (Buf, 0, Readbytes);
}
fsin.close ();
fSout.Close ();
Filestatus [] hadfiles = hadoopfs.liststatus (hadpath);
para (filestatus fs: hadfiles) {
System.out.println (fs.ToString ());
}
devolver verdadero;
} Catch (ioException e) {
E.PrintStackTrace ();
}
devolver falso;
}
Public Boolean Delfile (String Hadfile) {
intentar {
FileSystem hadoopfs = filesystem.get (conf);
Ruta hadpath = nueva ruta (hadfile);
Ruta p = hadpath.getParent ();
boolean rtnval = hadoopfs.delete (hadpath, verdadero);
Filestatus [] hadfiles = hadoopfs.liststatus (p);
para (filestatus fs: hadfiles) {
System.out.println (fs.ToString ());
}
return rtnval;
} Catch (ioException e) {
E.PrintStackTrace ();
}
devolver falso;
}
public boolean downloadfile (string hadfile, string localpath) {
intentar {
FileSystem localfs = filesystem.getLocal (conf);
FileSystem hadoopfs = filesystem.get (conf);
Ruta hadpath = nueva ruta (hadfile);
FsDataOutputStream fSout = localfs.create (nueva ruta (localpath+"/"+hadpath.getName ()));
Fsdatainputstream fsin = hadoopfs.open (hadpath);
byte [] buf = nuevo byte [1024];
int readbytes = 0;
while ((readbytes = fsin.read (buf))> 0) {
fSout.Write (Buf, 0, Readbytes);
}
fsin.close ();
fSout.Close ();
devolver verdadero;
} Catch (ioException e) {
E.PrintStackTrace ();
}
devolver falso;
}
}