java: 写入流后数据长度变化

java: Length of data changes after write in stream

我在FileOutputStream中保存了一个二进制数据,但是当我检查前后数据的长度时,发现它从72变成了106。 这是我的方法:

inputStream = new FileInputStream(certificate_file); 
/*Certificate file is a Path of a binary file */
pubkey = readFromStream(inputStream, 0, 71);

System.out.println("length of pubkey: "+pubkey.length());
/* This return : length of pubkey: 72 */

writeToStream(path + "pubkey.bin", pubkey);
inputStream = new FileInputStream(path + "pubkey.bin");
 pubkey = readFromStream(inputStream);
 System.out.println("length of pubkey: "+pubkey.length());
 /* This return : length of pubkey: 106 */

writeToStream 方法将数据写入输出流:

public void writeToStream(String path, String data)
        throws FileNotFoundException {
    OutputStream os = new FileOutputStream(path);
    PrintStream printStream = new PrintStream(os);
    printStream.print(data);
}

从流中读取数据的 readFromStream 方法:

  public static String readFromStream(InputStream inputStream, int begin, int end) throws Exception {

    int i = 0;
    int data = inputStream.read();
    String out = "";
    while (data != -1) {
        if (i >= begin && i <= end) {
            out += (char) data;
        }
        data = inputStream.read();
        i++;
    }

    return out;
}

    public static String readFromStream(InputStream inputStream) throws Exception {

    int i = 0;
    int data = inputStream.read();
    String out = "";
    while (data != -1) {

            out += (char) data;

        data = inputStream.read();
        i++;
    }

    return out;
}

为什么我有这个问题?

我已经解决了问题,我将数据从 String 转换为 bytes[],并将 readFromStream 中的读取更改为 readAllBytes。