java操作hdfs输出文件内容的方法
自定义了一个 inputToString的方法,代码可能写的不规范。。
//输出文件
@Test
public void redToString() throws IOException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
// 读取文件放到一个输入流中
FSDataInputStream inputStream = fs.open(new Path("/employee/java/employee.txt"));
//调用方法处理文件
String s1 = inputToString(inputStream,"UTF-8");
System.out.println("s1="+s1);
}
//私有的文件处理方法
private static String inputToString(InputStream inputStream,String encode){
try {
if(encode.equals("") && encode == null){
encode="utf-8";
}
//字符串缓冲流来处理字符流中的内容并指定编码
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,encode));
StringBuilder sb = new StringBuilder();
String ss = "";
// 循环读取缓冲流中的内容并添加到一个StringBuilder中,读取完一个换行
while (( ss=br.readLine())!= null){
sb.append(ss).append("\n");
}
// 以string类型返回读取完毕的内容
return sb.toString();
}catch (Exception e){
e.printStackTrace();
}
return null;
}