import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import java.io.InputStream;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;
public class HDFS {
public static void main(String[] args) throws Exception {
creatFile();
Configuration conf = new Configuration();
URI uri = new URI("hdfs://master:9000");
FileSystem fs = FileSystem.get(uri, conf, "root");
Path fpath =new Path("/user/ubuntn/file.txt");
FileStatus filestatus =fs.getFileLinkStatus(fpath);
long blocksize = filestatus.getBlockSize();
System.out.println("blocksize:"+blocksize);
long filesize = filestatus.getLen();
System.out.println("filesize:"+filesize);
String fileowner = filestatus.getOwner();
System.out.println("fileowner:"+fileowner);
SimpleDateFormat formatter =new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
long accessTime = filestatus.getAccessTime();
System.out.println("access time:"+formatter.format(new Date(accessTime)));
long modifyTime=filestatus.getModificationTime();
System.out.println("modify time:"+formatter.format(new Date(modifyTime)));
}
public static void creatFile() throws Exception {
Configuration conf = new Configuration();
URI uri = new URI("hdfs://master:9000");
FileSystem fs = FileSystem.get(uri, conf, "root");
System.out.println(fs.toString());
Path dfs = new Path("/user/1207.txt");
FSDataOutputStream newFile = fs.create(dfs, true);
newFile.writeBytes("hello,hdfs!");
newFile.flush();
newFile.close();
}
public static void deleteFile() throws Exception{
Configuration conf = new Configuration();
URI uri = new URI("hdfs://master:9000");
FileSystem fs = FileSystem.get(uri, conf, "root");
Path path = new Path("/user/1207.txt");
fs.delete(path,true);
}
public static void uploadFile() throws Exception{
Configuration conf = new Configuration();
URI uri = new URI("hdfs://master:9000");
FileSystem fs = FileSystem.get(uri, conf, "root");
Path src= new Path("/home/flie.txt");
Path dst = new Path("/user/1207.txt");
fs.copyFromLocalFile(src,dst);
}
public static void downloadFile() throws Exception{
Configuration conf = new Configuration();
URI uri = new URI("hdfs://master:9000");
FileSystem fs = FileSystem.get(uri, conf, "root");
Path src= new Path("/home/flie.txt");
Path dst = new Path("/user/1207.txt");
fs.copyToLocalFile(src,dst);
}
public static void readFile() throws Exception{
Configuration conf = new Configuration();
URI uri = new URI("hdfs://master:9000");
FileSystem fs = FileSystem.get(uri, conf, "root");
Path path;
path = new Path("/user/1207/file.txt");
InputStream is = fs.open(path);
IOUtils.copyBytes(is,System.out,conf);
IOUtils.closeStream(is);
}
}