【问题标题】:Have a greater number than 256 android file output stream具有大于 256 的 android 文件输出流
【发布时间】:2014-05-17 23:16:59
【问题描述】:

我正在使用fos.write(some_number) 但是当我尝试显示该数字时,它不会大于 255。

这是第二个活动的代码:

        FileOutputStream fos;
        try {
            fos = openFileOutput("Income", Context.MODE_PRIVATE);
//"Income" is the number that is written on the TextField
            fos.write(Income);
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

第一个活动的代码:

try {
        FileInputStream fis;
        fis = openFileInput("Income");
        TOTAL_INCOME = fis.read();
        fis.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //...
    //....


  TextView textView = (TextView) findViewById(R.id.IncomeValue);
  textView.setText(""+ TOTAL_INCOME);

【问题讨论】:

    标签: java android io


    【解决方案1】:

    write() 方法只写入一个范围为 0-255 的字节,因此您不会得到更多。

    最好使用DataOutputStreamDataInputStream 喜欢:

    FileOutputStream fos;
    try {
    fos = openFileOutput("Income", Context.MODE_PRIVATE);
    DataOutputStream dos = new DataOutputStream(fos);
    dos.writeInt(Income);
    dos.close();
    fos.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    

    第一个活动:

    try {
    FileInputStream fis;
    fis = openFileInput("Income");
    DataInputStream dis = new DataInputStream(fis);
    TOTAL_INCOME = dis.readInt();
    dis.close();
    fis.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    TextView textView = (TextView) findViewById(R.id.IncomeValue);
    textView.setText(""+ TOTAL_INCOME);
    

    【讨论】:

      【解决方案2】:

      如果您查看FileOutputStream#write() 的javadoc,您会注意到它只写出一个字节,其范围为0-255(含)。这就是为什么您永远不会看到大于 255 的数字。

      【讨论】:

      • 感谢您的回复。你能告诉我一种能够保存大于 255 的数字的方法吗?
      • 您不能直接操作,因为FileOutputStream 直接对文件的字节进行操作。您需要弄清楚如何一次存储/检索多个字节,以便可以表示具有更大范围的数字。
      猜你喜欢
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 2013-10-01
      相关资源
      最近更新 更多