有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

这是我的C://测试文件。组成 溴化二苯醚 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();
}

请帮我解决我的问题


共 (2) 个答案

  1. # 1 楼答案

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

    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设置文件的偏移量,然后开始读取

  2. # 2 楼答案

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

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