InputStream读取函数

时间:2016-03-18 15:36:16

标签: java int byte inputstream javadoc

我有以下代码从文件中读取字节并将其打印出来:

public static void main(String[] args) throws FileNotFoundException, IOException {

    try (InputStream is = new FileInputStream("myFile")) {
        byte[] bytes = new byte[3];
        while (is.read(bytes) != -1) {
            System.out.println("bytes = " + Arrays.toString(bytes));
        }
    }
}

以下是myFile的内容:

AAABBB|||ùùù

这是输出:

bytes = [65, 65, 65]
bytes = [66, 66, 66]
bytes = [124, 124, 124]
bytes = [-7, -7, -7]

我的问题是,由于字节的范围值是-128到127,因此在输出中看到负值是正常的。尽管如此, InputStream.read()方法的javadoc说

  

值字节作为int返回,范围为0到255

这不是有点模棱两可吗? int(0到255)如何映射到字节(-128到127)?

感谢。

1 个答案:

答案 0 :(得分:0)

首先,您致电int read()而不是 try (InputStream is = new FileInputStream("myFile")) { int i; while (true) { i = is.read(); if (i == -1) break; System.out.println(i); } } 。你可以通过以下方式查看:

ùùù

和第二,也许你会对字节大小感到好奇,因为Java是unicode字符,每个unicode字符需要 view_object(driver, type, address): strategy = { "css_selector": driver.find_element_by_css_selector, "id": driver.find_element_by_id, "link_text": driver.find_element_by_link_text, "name": driver.find_element_by_name, "xpath": driver.find_element_by_xpath } lhsType, rhsType = type.split(".", 1) find_element = strategy.get(rhsType.lower()) obj = find_element(address) driver.execute_script("return arguments[0].scrollIntoView();", obj) 中的2个字节