HDFSUtil
package com.zhph.hadoop;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
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.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
/**
* @ClassName:HDFSUtil
* @Description:hadoop hafs 文件操作工具类
* @company:zhph
* @author Even
* @date 2016年7月27日 下午2:00:51
*/
public class HDFSUtil {
private static Configuration conf = new Configuration();
static {
conf.addResource("hdfs.xml");
// 代码配置环境变量,以免报 " Could not locate executable null\bin\winutils.exe in the Hadoop binaries."异常,其实不会影响功能
System.setProperty("hadoop.home.dir", "D:\\hadoop\\hadoop-2.4.0");
}
/**
* @Title: uploadFileFromLocation
* @param: in 上传文件输入流
* @param: filePath 文件上传到hdfs上的保存路径("/upload/")
* @param: fileName 文件名字
* @return:void
* @Description:TODO 上传文件到dataNode
* @author Even
* @date 2016年7月27日 下午2:03:37
* @throws
*/
public static void uploadFileFromLocation(InputStream in, String filePath) {
FileSystem fs = null;
FSDataOutputStream out = null;
try {
fs = FileSystem.get(conf);
Path path = new Path(filePath);
out = fs.create(path);
fs.setReplication(path, (short)2); // 在hdfs集群上保存的份数,2份
IOUtils.copyBytes(in, out, 1024);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
out.flush();
out.close();
fs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* @Title: downLoadFile
*