从文本文件中编写和阅读 - Android

时间:2013-10-01 22:49:41

标签: android android-file

我有类,应该能够读取和写入文件:

 public class CacheOperator {

Context c;

public CacheOperator(Context context) {
    this.c = context;
}

public void saveSth() {
    String FILENAME = "file.txt";
    String string = "hello world!";

    FileOutputStream fos = null;
    try {
            fos = c.openFileOutput(FILENAME, Context.MODE_PRIVATE);
            fos.write(string.getBytes());
            fos.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
}

public String readSth() {
    String FILENAME = "file.txt";
    String readStr = new String();

    FileInputStream fis = null;
    try {
            fis = c.openFileInput(FILENAME);
            fis.read(readStr.getBytes());
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    return readStr;
}

}

在活动中呼叫:

    CacheOperator co = new CacheOperator(this);
    co.saveSth();

    cachedValue = co.readSth();

    System.out.println(cachedValue);

和CachedValue是“”。 这是为什么?我以为我在“file.txt”中写了“hello world”。

0 个答案:

没有答案