Android Studio: Custom Writer Class extends BufferedWriter (PemWriter)

216 views Asked by At

The following is an example of the class that I have to use. I've generalized the names to get at the concept rather than the my particular use. I'm trying to figure out how to use it. So, I can't change this part, only what's in my activity:

public class MyWriter extends BufferedWriter {

public MyWriter(Writer out)
{
    super(out);
}

public void writeTest(String repeatthis) throws IOException {
    this.write(repeatthis);
    this.newLine();
    this.write("along with this other stuff.");
}
}

This is what's in my activity:

    String iwantThisString = "";
    StringWriter writer = new StringWriter();
    MyWriter myWriter = new MyWriter(writer);
    String myNewString = "I want to see this repeated back to me.";

    try {
        myWriter.writeTest(myNewString);
        iwantThisString = writer.toString();  //Does not work.
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

How do I get iwantThisString, to pick up what writeTest is laying down?

If you want to see the actual class that I'm trying to use, it's the pemWriter from Spongy Castle.

2

There are 2 answers

0
Adam Winter On

Also, I've found that the following code does work with the spongy castle library, taken from: Export RSA public key to PEM String using java

    PublicKey publicKey = keyPair.getPublic();
    StringWriter writer = new StringWriter();
    PemWriter pemWriter = new PemWriter(writer);
    pemWriter.writeObject(new PemObject("PUBLIC KEY", publicKey.getEncoded()));
    pemWriter.flush();
    pemWriter.close();
    return writer.toString();
0
Adam Winter On

Forgot to flush the buffered writer as MyWriter extends BufferedWriter.

    StringWriter writer = new StringWriter();
    MyWriter myWriter = new MyWriter(writer);
    String myNewString = "I want to see this repeated back to me.";

    try {
        myWriter.writeTest(myNewString);
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        myWriter.flush();
        myWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return writer.toString();