[英]Android file writing/reading
It's shows me some letters and numbers when i enter a number in the TextField for example i will type 100 and it gives me letter "d" how can i fix this ? 当我在TextField中输入数字时,它向我显示了一些字母和数字,例如,我将键入100并给我字母“ d”,我该如何解决呢? I have this code. 我有这个代码。
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();
}
}
});
Explain me whats causes this problem and how do i fix it ... thanks :) 向我解释是什么导致了此问题,以及如何解决它...谢谢:)
100 is the ASCII value for d. 100是d的ASCII值 。 Your string value is being type casted to its ASCII value at the OutputStream
. 您的字符串值将在OutputStream
上类型转换为其ASCII值。
You cannot write strings in OutputStream
directly. 您不能直接在OutputStream
编写字符串。 Try: 尝试:
outputStream.write(txtEdit.getText().toString().getBytes());
To limit your inputs to numbers, you can specify the keyboard. 要将输入限制为数字,可以指定键盘。 See the TextFields documentation . 请参阅TextFields文档 。
Ex 1: 例1:
<EditText
android:id="@+id/numberInput"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/number_hint"
android:inputType="number" />
Ex 2 - Phone Dialer Keyboard: 例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)
is writing that int
as byte, so if you write .write(100)
and later you read as string
you will get d
since 100
is the ASCII code for d
. OutputStream.write(int)
被编写int
为字节,因此,如果你写.write(100)
后来又读作string
你会得到d
,因为100
是ASCII码d
。 If you try 101
it then will be e
. 如果尝试101
,则为e
。
If you want to save 100
as "100"
then try: How to write Strings to an OutputStream 如果要将100
保存为"100"
尝试: 如何将字符串写入OutputStream
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.