hdfsAPI

版权声明:该版权归博主个人所有,在非商用的前提下可自由使用,转载请注明出处. https://blog.csdn.net/qq_24696571/article/details/86831929
  • 通过代码操作hdfs系统上的数据文件
package com.credi;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
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;

/**
 * 
 * 需要导入hadoop解压的jar包
 * 需要将hadoop-2.6.5/etc/hadoop目录下配置好的 hdfs-site.xml和core-site.xml拷贝到src目录下
 * 
 * @author credi He
 *
 */
public class TestHdfs {
	
	public static void main(String[] args) throws Exception {
		//配置类
		Configuration conf = new Configuration();
		//FileSystem 加载配置类的信息
		FileSystem fs = FileSystem.get(conf);
		
		//1 . 创建文件夹
		//mkdirs_file(fs,"/hdfs/test");
		//2 . 删除文件
		//delete_file(fs);
		//3 . 上传文件
		//upload_file(fs, conf);
		//4 . 下载文件
		//download_file(fs, conf);
		//5 . 查看详细信息
		status_file(fs);
	}
	
	//从HDFS下载文件(hdfs读的流程)
	static void download_file(FileSystem fs ,Configuration conf) throws IOException {
		Path path = new Path("/jc/hdfsAPI.txt"); 			//要下的文件在hdfs的位置
		File file = new File("d:/downloadToHdfs.txt");		//要下载到的本地路径
		FSDataInputStream in = fs.open(path);				//读文件流 , 从hdfs读
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));	//写到本地磁盘的哪里
	
		IOUtils.copyBytes(in, out, conf);   				//文件从哪里读,写到哪里,服务器配置
	}
	
	//向HDFS上传文件(hdfs写的流程)
	static void upload_file(FileSystem fs , Configuration conf) throws IOException{
		Path path = new Path("/hdfs/test/hdfsAPI.txt");			//文件上传到HDFS哪里
		File file = new File("D:/hdfsAPI.txt");				//上传的文件在本地路径的哪里
		
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));	//从哪里读
		FSDataOutputStream out = fs.create(path);   		//上传到哪里
		
		IOUtils.copyBytes(new FileInputStream(file), out, conf);	//文件从哪里读,读到哪里去 , 服务器的相关配置信息
		
	}
	
	//在HDFS创建文件夹
	static void mkdirs_file(FileSystem fs , String filename) throws IOException {
		//在hdfs上创建文件夹
		fs.mkdirs(new Path(filename));
	}
	
	//在HDFS删除文件夹
	static void delete_file(FileSystem fs) throws IllegalArgumentException, IOException{
		fs.delete(new Path("/jc"), true);
	}
	
	//查看HDFS详细信息
	static void status_file(FileSystem fs) throws Exception{
		Path path = new Path("/hdfs");
		FileStatus[] fileStatus = fs.listStatus(path);   //要查看的路径信息 , 返回的FileStatus对象包含了要查询的信息
		
		for(FileStatus fstatus : fileStatus){
			System.out.println(
				
					"文件创建时间:" + new Date(fstatus.getAccessTime()) +
					"文件修改时间:" + new Date(fstatus.getModificationTime()) + 
					"文件大小:" + fstatus.getBlockSize()/1024/1024 + "MB" +
					"文件所有者:" + fstatus.getOwner()
					
			);
		}
	}

}

猜你喜欢

转载自blog.csdn.net/qq_24696571/article/details/86831929