我正在尝试使用android.os.memoryfile写入一个文件,然后从相同的文件中读取。我用一种方法写入文件并从另一种方法读取,全部在同一个类中。我可以写得很好,但是当我读取文件时,我得到了符号的行,而不是我写入文件的内容。看来,这个读取方法并没有读取我写过的文件。使用android.os.memoryfile的文件IO
如果我把代码写入和读取文件的方法相同,它似乎工作正常。读取文件输出我写的字符串。
这是我的代码:
public class FileActivity extends Activity {
MemoryFile memFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
memFile = new MemoryFile("MemoryFileTest", 1000000);
} catch (IOException e) {
e.printStackTrace();
}
}
public void readFile() {
StringBuffer strBuffer = new StringBuffer();
try {
InputStream in = memFile.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String inputString;
while ((inputString = reader.readLine()) != null) {
strBuffer.append(inputString + "\n");
}
in.close();
reader.close();
Log.d(TAG, strBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeFile() {
String example = "This is an example";
byte[] bytes = example.getBytes();
try {
OutputStream out = memFile.getOutputStream();
out.write(bytes);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的代码中,MemoryFile在类的顶部声明,并且在onCreate()方法初始化。然后我试图用这个MemoryFile编写和阅读。
我在这里错过了什么?
我通过调用'writeFile()'和'readFile()'在'onCreate()'的末尾添加了你的代码。我在'logcat'输出中看到了示例文本。示例文本的结尾是一串长长的符号,它们是黑色钻石中的问号。你看到没有文字输出吗?只是钻石问号? –
是的,我只看到带有上述代码的钻石问号。如果我将写入和读取代码放在一个方法中,我确实得到了原始字符串,没有任何菱形问号。 – user695752
我的回答有用吗? –