0

如何从内部存储文件中读取特定数据。例如,我存储了 1. 设备 2. 时间(纪元格式) 3. 按钮文本

            CharSequence cs =((Button) v).getText();
            t = System.currentTimeMillis()/1000;
    s = cs.toString();
    buf = (t+"\n").getBytes();
    buf1 = (s+"\n").getBytes();


    try {
        FileOutputStream fos = openFileOutput(Filename, Context.MODE_APPEND);
        fos.write("DVD".getBytes());
        fos.write(tab.getBytes());
        fos.write(buf);
        fos.write(tab.getBytes());
        fos.write(buf1);
        //fos.write(tab.getBytes());
        //fos.write((R.id.bSix+"\n").getBytes());
        fos.write(newline.getBytes());
        //fos.flush();
        fos.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

那么在阅读时,我们如何才能从文件中只读取价格呢?(使用 fos.read())

谢谢

4

1 回答 1

0

我建议以更结构化的方式编写文件,如下所示:

long t = System.currentTimeMillis()/1000;
String s = ((Button) v).getText();
DataOutputStream dos = null;
try {
    dos = new DataOutputStream(openFileOutput(Filename, Context.MODE_APPEND));
    dos.writeUTF("DVD");
    dos.writeLong(t); // Write time
    dos.writeUTF(s); // Write button text
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} finally {
    if (dos != null) {
        try {
            dos.close();
        } catch (IOException e) {
            // Ignore
        }
    }
}

要读回来,是这样的:

DataInputStream dis = null;
try {
    dis = new DataInputStream(openFileInput(Filename));
    String dvd = dis.readUTF();
    long time = dis.readLong();
    String buttonText = dis.readUTF();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (dis != null) {
        try {
            dis.close();
        } catch (IOException e) {
            // Ignore
        }
    }
}
于 2012-07-19T19:23:01.730 回答