FSDataInputStream也实现了Positionreadable接口,指从指定偏移量处读取数据。
hdfs中文件数据为:
首先对第一个方法进行测试:
package test01;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
public class test02 {
public static void main(String[] args) throws Exception {
Configuration conf=new Configuration();
URI uri=new URI("hdfs://192.168.137.128:8020");
FileSystem fs=FileSystem.get(uri, conf);
FSDataInputStream in= fs.open(new Path("/test.txt"));
System.out.println("文件的总大小为:"+in.available());
//首先读取全部内容:
IOUtils.copyBytes(in, System.out, in.available());
//重新定位:
in.seek(0);
//创建一个27长度的byte数组
byte[] buffer=new byte[27];
//in.read(position, buffer, offset, length)
in.read(0, buffer, 0, 27);
System.out.println(new String(buffer));
//从第1为开始,从数组的第1为开始,读取长度26,从buffer中的第一位开始存取
byte[] buffer1=new byte[27];
in.seek(0);
in.read(2,buffer1,1,26);
System.out.println(new String(buffer1));
//重新定位,测试readFully(position, buffer)只读取buffer.length的长度的数据
in.seek(0);
byte[] buffer3=new byte[26];
in.readFully(1, buffer3);
System.out.println(new String(buffer3));
in.close();
fs.close();
}
}
输出结果为:
由上分析可知:
第一个方法是从某个位置(position)开始读取自定义的长度(legth),然后从数组的某个位置(offset)开始存取数据
最后一个方法是从某个位置开始,读取buffer.length个长度