Search code examples
javafileoutputstreamprintstream

java: Length of data changes after write in stream


I have saved a binary data in FileOutputStream but when I check the length of the data before and after I found that it changes from 72 to 106. This is my method:

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 method to write data into outputstream:

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

readFromStream method to read data from stream:

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

Why I have this problem?


Solution

  • I have solved the problem, I transformed the data from String to bytes[] and I changed the read in readFromStream to readAllBytes.