Java 如何在输入流中间读取偏移量?

Java 如何在输入流中间读取偏移量?,java,byte,inputstream,fileinputstream,Java,Byte,Inputstream,Fileinputstream,这是我的文件C://test.txt,由 溴化二苯醚 FGHIJ 我想从F一直读到J。 所以输出是FGHIJ。我将如何在使用偏移量的InputStream读取中执行此操作。 这是我的部分实现 InputStream is = null; byte[] buffer = null; char c; try { is = new FileInputStream("D://test.txt"); buffer = new byte[is.available()]; Syste

这是我的文件C://test.txt,由 溴化二苯醚 FGHIJ

我想从F一直读到J。 所以输出是FGHIJ。我将如何在使用偏移量的InputStream读取中执行此操作。 这是我的部分实现

InputStream is = null;
byte[] buffer = null;
char c;

try {
    is = new FileInputStream("D://test.txt");
    buffer = new byte[is.available()];
    System.out.println("Characters printed:");
    is.read(buffer, 5, 5);
    for (byte b : buffer) {

        if (b == 0)
            // if b is empty
            c = '-';
        else
            c = (char) b;

        System.out.print(c);
        }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (is != null)
        is.close();
}
请帮我解决我的问题:D

看,第二个参数是“目标数组中的起始偏移量”不是文件偏移量,我想你弄错了,所以你可以尝试读取所有这些,然后找到第一个空格字符,然后开始打印,如下所示:

InputStream is = null;
    byte[] buffer = null;
    char c;
    boolean canPrint = false;

    try {
        is = new FileInputStream("/Users/smy/test.txt");
        buffer = new byte[is.available()];
        System.out.println("Characters printed:"+is.available());
        is.read(buffer, 0, is.available());
        for (byte b : buffer) {

            if ((char)b == ' ')
                // if b is empty
                canPrint = true;
            else{
                c = (char) b;

                if (canPrint){
                    System.out.print(c);
                }}
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

或者,您可以使用设置文件的偏移量,然后开始读取。

如果要从第n个字符开始,可以执行以下操作:

 public static void file_foreach_offset( String file, int offset, IntConsumer c) throws IOException {

        try(Stream<String> stream = Files.lines(Paths.get(file))) {
            stream.flatMapToInt(String::chars)
                  .skip(offset)
                  .forEach(c);
        }
    } 
public static void file\u foreach\u offset(字符串文件,int offset,intc)引发IOException{
try(Stream=Files.line(path.get(file))){
stream.flatMapToInt(字符串::字符)
.跳过(偏移)
.forEach(c);
}
} 

读取()的
偏移量
参数是缓冲区中的偏移量,而不是文件。您要查找的是
seek()
方法,后面是偏移量为零的
read()


注意:这是对
available()
的典型误用。请参阅Javadoc。有一个特别的警告,不要将其用作输入流的长度。

实际上,要求使用的源是inputstream。然后遍历它或者在字节的中间读它。如果你不能用偏移量访问流,你可以像我的代码一样逐一读取它。