hadoop深入浅出-JAVA操作HDFS(JAVA接口使用),hadoophdfs
分享于 点击 6336 次 点评:282
hadoop深入浅出-JAVA操作HDFS(JAVA接口使用),hadoophdfs
package sunyuqiang.com;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class App
{
public static void main( String[] args ) throws IOException {
testGet();//测试读取
System.out.println("_____________________________");
testPut();//测试写入
}
public static void testGet() throws IOException
{
//连接HDFS系统
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS","hdfs://sunyuqiang.com:9000");
//获得文件系统对象
FileSystem fileSystem = FileSystem.get(configuration);
//指定文件路径对象
String filePath = "/user/hadoop/mapreduce/wordcount/input/my.txt";
Path readPath = new Path(filePath);
//open()文件流,获得输入流对象
FSDataInputStream inputStream = fileSystem.open(readPath);
//输出文件信息
try{
IOUtils.copyBytes(inputStream,System.out,4096,false);
}catch (Exception e){
e.printStackTrace();
}finally {
IOUtils.closeStream(inputStream);
}
}
public static void testPut() throws IOException
{
//连接HDFS系统
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS","hdfs://sunyuqiang.com:9000");
//获取文件对象
FileSystem fileSystem = FileSystem.get(configuration);
//准备本地文件流
String localFilePath = Hdfs.class.getClassLoader().getResource("my.log").getPath();
System.out.println(localFilePath); //查看本地路径
FileInputStream inputStream = new FileInputStream(new File(localFilePath));
//准备PUT文件路径对象
String hdfsDirPath = "/user/hadoop/mapreduce/wordcount/input/my.log";
Path path = new Path(hdfsDirPath);
//获得输出流对象
FSDataOutputStream outputStream = fileSystem.create(path);
//PUT写入文件
try{
IOUtils.copyBytes(inputStream,outputStream,4096,false);
}catch (Exception e){
e.printStackTrace();
}finally {
IOUtils.closeStream(inputStream);
IOUtils.closeStream(outputStream);
}
}
}
运行查看结果如下图:
程序读取到HDFS文件系统中文件的内容,并且无错误的返回了。那就去查看下HDFS中有没有成功上传my.log文件
未执行程序时
执行程序后
这里不知道为什么上传后所有者是乱码的,以后解决吧!
相关文章
- 暂无相关文章
用户点评