繁体   English   中英

Android文件读写

[英]Android file writing/reading

当我在TextField中输入数字时,它向我显示了一些字母和数字,例如,我将键入100并给我字母“ d”,我该如何解决呢? 我有这个代码。

btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int takeMoney = Integer.parseInt(txtEdit.getText().toString());
            String filename = "moneySavings.txt";
            int asd = takeMoney;
            FileOutputStream outputStream;

            try {
                outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
                outputStream.write(asd);
                outputStream.close();
                savings.setText("File Created !");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            FileInputStream fis;
            final StringBuffer storedString = new StringBuffer();

            try {
                fis = openFileInput("moneySavings.txt");
                DataInputStream dataIO = new DataInputStream(fis);
                String strLine = null;

                if((strLine = dataIO.readLine()) != null) {
                    storedString.append(strLine);
                    savings.setText(strLine);
                }
                dataIO.close();
                fis.close();
            }
            catch  (Exception e) {
                e.printStackTrace();
            }
        }
    });

向我解释是什么导致了此问题,以及如何解决它...谢谢:)

100是d的ASCII值 您的字符串值将在OutputStream上类型转换为其ASCII值。

您不能直接在OutputStream编写字符串。 尝试:

outputStream.write(txtEdit.getText().toString().getBytes());

要将输入限制为数字,可以指定键盘。 请参阅TextFields文档

例1:

<EditText
    android:id="@+id/numberInput"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/number_hint"
    android:inputType="number" />

例2-电话拨号键盘:

<EditText
    android:id="@+id/numberInput"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/number_hint"
    android:inputType="phone" />

OutputStream.write(int)被编写int为字节,因此,如果你写.write(100)后来又读作string你会得到d ,因为100是ASCII码d 如果尝试101 ,则为e

如果要将100保存为"100"尝试: 如何将字符串写入OutputStream

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM