本地电脑连接指定集群的代码:
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上删除和新建时,需要打开操作文件下的权限:
“hdfs dfs -chmod
777
/input”打开权限,这样才可以删除其下面的文件
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(); } }
原文:http://wukong0716.blog.51cto.com/10442773/1699364