java 安卓开发之文件的读与写

java文件的读与写,代码:

String file="user.txt";
private void writeFileData(String str1, String str2) throws IOException {
// TODO Auto-generated method stub FileOutputStream outputStream = openFileOutput(file,
Activity.MODE_PRIVATE);
outputStream.write(str1.getBytes());
outputStream.write("#".getBytes());
outputStream.write(str2.getBytes());
outputStream.flush();
outputStream.close();
Toast.makeText(helloworld.this, "保存成功", Toast.LENGTH_LONG).show();
}
private String readFileData(String file) throws IOException {
// TODO Auto-generated method stub String display;
FileInputStream inputStream = this.openFileInput(file);
byte[] bytes = new byte[1024];
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
while (inputStream.read(bytes) != -1) {
arrayOutputStream.write(bytes, 0, bytes.length);
}
inputStream.close();
display = new String(arrayOutputStream.toByteArray());
return display;
}

  值得注意的是在读取文件的时候,display后跟了空格,在进行字符串比较的时候必须去掉这个空格,即用trim()方法。

    private void login() throws IOException {
// TODO Auto-generated method stub
getData();
String str=readFileData(file);
String[] strarray=str.split("#");
String str0=strarray[].trim();
String str1=strarray[].trim();
if(str0.equals(str_name)&&str1.equals(str_pd))
Toast.makeText(helloworld.this, "登录成功 ",Toast.LENGTH_LONG).show();
else
Toast.makeText(helloworld.this, "登录失败 ",Toast.LENGTH_LONG).show();
}

如上代码所示。str1必须加trim(),不然str1.equals(str_pd)会返回为false。

上一篇:对Google cloud platform 做了点研究


下一篇:点击后打开QQ临时会话