您的位置:首页 > 编程语言 > Java开发

学习日志---本地javaApi连接集群hdfs

2015-09-30 08:05 585 查看
本地电脑连接指定集群的代码:

public class Tt_one {

public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://hadoop1:9000");
FileSystem hdfs = FileSystem.get(conf);
FSDataInputStream in1 = null;
in1 = hdfs.open(new Path("/input/t1.txt"));
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
String line = br1.readLine();
System.out.println(line);
}
}
本地删除和添加集群文件
这里实现的是把hdfs上一个文件删除,并新建,然后把hdfs上的一个文件复制到该文件中。
需要注意的是:hdfs上删除和新建时,需要打开操作文件下的权限:
package bbdt.steiss.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class Tt_one {

public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://hadoop1:9000");
FileSystem fs = FileSystem.get(conf);
FSDataInputStream in1 = null;
in1 = fs.open(new Path("/output/part-r-00000"));
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
fs.delete(new Path("/input/test2.txt"),true);
FSDataOutputStream fsDataOutputStream = fs.create(new Path("/input/test2.txt"));
BufferedWriter bw1 = new BufferedWriter(new OutputStreamWriter(fsDataOutputStream));
String s1 = null;
while ((s1 = br1.readLine()) != null)
{
bw1.write(s1);
bw1.write("\n");
}
bw1.close();
fsDataOutputStream.close();
br1.close();
in1.close();

}
}
创建FileSystem的方法:
上面是一种,这里也是一种
DirFile为hdfs的入口地址,如
hdfs://hadoop1:9000
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(DirFile), conf);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hadoop