以下是我必须使用的类的示例。我正在尝试弄清楚如何使用它。因此,我无法更改此部分,只能更改活动中的内容:
package com.example.android.datafrominternet.utilities;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
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.");
Log.d("LOOK HERE", "writeTest was accessed successfully"+repeatthis);
}
}
这是我的活动:
String iwantThisString = "";
StringWriter writer = new StringWriter();
MyWriter myObjectWrites = new MyWriter(writer);
String myNewString = "I want to see this repeated back to me.";
try {
myObjectWrites.writeTest(myNewString);
iwantThisString = writer.toString(); //Does not work.
} catch (IOException e) {
e.printStackTrace();
}
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
如何获取iwantThisString,以获取writeTest放置的内容?
如果您想查看我要使用的实际类,那就是Spongy Castle的pemWriter。
答案 0 :(得分:0)
此外,我发现以下代码可用于海绵城堡库,该库取自: 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();
答案 1 :(得分:0)
据我所知,这是如何工作的完整解释(现在我已经知道了):
public class MyWriter extends BufferedWriter {
在创建扩展BufferedWriter的类MyWriter时,MyWriter变成与BufferedWriter相同的类,直到您更改某些内容。
public MyWriter(Writer out)
{
super(out);
}
这是构造函数。它看起来像一个方法/函数,但是只有在您创建“新的MyWriter”时才被调用,并根据这些说明定义新对象。在这种情况下,创建MyWriter的新实例需要输入参数'(Writer out)',该参数是活动中名为'writer'的StringWriter。也就是说,它需要另一个Writer作为输入并将其称为“输出”。 “超级”将“输出”发送到BufferedWriter。为此,您已将StringWriter“包装”在BufferedWriter中。换句话说,您已将StringWriter放入BufferedWriter中。结果结合了两种Writer的功能。如果愿意,可以使用“缓冲字符串编写器”。
public MyWriter writeTest(String repeatthis) throws IOException {
this.write(repeatthis);
this.newLine();
this.write("along with this other stuff.");
这里要注意的重要一点是,“ this”是指BufferedWriter。实质上是将每个字符串附加到BufferedWriter内部存在的未命名字符串。
最重要的是,您必须使用'flush()'将所有内容转储到BufferedWriter中,以将其放到预期的位置。在这种情况下,“ flush()”最终将字符串发送到StringWriter,它将保留在那里,直到将其从此处拉出为止。以下是正确的工作代码:
StringWriter writer = new StringWriter();
MyWriter myObjectWrites = new MyWriter(writer);
String myNewString = "I want to see this repeated back to me.";
try {
myObjectWrites.writeTest(myNewString);
} catch (IOException e) {
e.printStackTrace();
}
try {
myObjectWrites.flush();
myObjectWrites.close();
} catch (IOException e) {
e.printStackTrace();
}
return writer.toString();
请注意,您关闭()BufferedWriter对象'myObjectWrites'而不是StringWriter对象'writer'。另外,根据文档,“ close()”还会刷新BufferedWriter,但为了安全起见,我仍在使用“ flush()”。