【问题标题】:how to read offset in the middle of an InputStream?如何读取 InputStream 中间的偏移量?
【发布时间】:2016-01-22 03:31:50
【问题描述】:

这是我的文件 C://test.txt 组成 ACBDE 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

【问题讨论】:

    标签: java byte inputstream fileinputstream


    【解决方案1】:

    read()offset 参数是缓冲区的偏移量,而不是文件的偏移量。您正在寻找的是seek() 方法,后跟一个偏移量为零的read()

    NB 这是对available() 的典型误用。请参阅 Javadoc。有一个特定的警告,禁止将其用作输入流的长度。

    【讨论】:

      【解决方案2】:

      如果你想从第 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);
              }
          } 
      

      【讨论】:

        【解决方案3】:

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

        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();
                    }
            }
        

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

        【讨论】:

        • 实际上,要求是使用输入流。然后遍历它或在字节中间的某个地方读取它..
        • 如果你无法访问带偏移量的流,你可以像我的代码显示的那样一一读取。
        猜你喜欢
        • 2012-10-20
        • 1970-01-01
        • 2021-08-08
        • 1970-01-01
        • 1970-01-01
        • 2012-03-29
        • 2012-04-28
        • 2021-04-07
        • 1970-01-01
        相关资源
        最近更新 更多