ตัวอย่างการดำเนินการไฟล์ HDFS รวมถึงการอัปโหลดไฟล์ไปยัง HDFS การดาวน์โหลดไฟล์จาก HDFS และการลบไฟล์บน HDFS
การคัดลอกรหัสมีดังนี้:
นำเข้า org.apache.hadoop.conf.configuration;
นำเข้า org.apache.hadoop.fs.*;
นำเข้า Java.io.File;
นำเข้า java.io.ioException;
ชั้นเรียนสาธารณะ hadoopfile {
การกำหนดค่าส่วนตัว conf = null;
public hadoopfile () {
conf = การกำหนดค่าใหม่ ();
conf.addresource (เส้นทางใหม่ ("/hadoop/etc/hadoop/core-site.xml"));
-
Public Hadoopfile (Configuration Conf) {
this.conf = conf;
-
SendFile บูลีนสาธารณะ (เส้นทางสตริง, สตริง localfile) {
ไฟล์ไฟล์ = ไฟล์ใหม่ (localFile);
if (! file.isfile ()) {
System.out.println (file.getName ());
กลับเท็จ;
-
พยายาม {
ระบบไฟล์ localfs = filesystem.getLocal (conf);
ระบบไฟล์ hadoopfs = filesystem.get (conf);
PATH HADPATH = เส้นทางใหม่ (เส้นทาง);
fsDataOutputStream fsout = hadoopfs.create (เส้นทางใหม่ (พา ธ+"/"+file.getName ()));
fsdatainputstream fsin = localfs.open (เส้นทางใหม่ (localfile));
ไบต์ [] buf = ไบต์ใหม่ [1024];
int readbytes = 0;
ในขณะที่ ((readbytes = fsin.read (buf))> 0) {
fsout.write (buf, 0, readbytes);
-
fsin.close ();
fsout.close ();
filestatus [] hadfiles = hadoopfs.liststatus (hadpath);
สำหรับ (filestatus fs: hadfiles) {
System.out.println (fs.toString ());
-
กลับมาจริง;
} catch (ioexception e) {
E.PrintStackTrace ();
-
กลับเท็จ;
-
Public Boolean delfile (String hadfile) {
พยายาม {
ระบบไฟล์ hadoopfs = filesystem.get (conf);
PATH HADPATH = เส้นทางใหม่ (HADFILE);
PATH P = HADPATH.GETPARENT ();
บูลีน rtnval = hadoopfs.delete (hadpath, true);
filestatus [] hadfiles = hadoopfs.liststatus (p);
สำหรับ (filestatus fs: hadfiles) {
System.out.println (fs.toString ());
-
กลับ rtnval;
} catch (ioexception e) {
E.PrintStackTrace ();
-
กลับเท็จ;
-
Public Boolean downloadfile (String hadfile, String localpath) {
พยายาม {
ระบบไฟล์ localfs = filesystem.getLocal (conf);
ระบบไฟล์ hadoopfs = filesystem.get (conf);
PATH HADPATH = เส้นทางใหม่ (HADFILE);
fsdataOutputStream fsout = localfs.create (เส้นทางใหม่ (localpath+"/"+hadpath.getName ()));
fsdatainputstream fsin = hadoopfs.open (hadpath);
ไบต์ [] buf = ไบต์ใหม่ [1024];
int readbytes = 0;
ในขณะที่ ((readbytes = fsin.read (buf))> 0) {
fsout.write (buf, 0, readbytes);
-
fsin.close ();
fsout.close ();
กลับมาจริง;
} catch (ioexception e) {
E.PrintStackTrace ();
-
กลับเท็จ;
-
-