0

我正在编写一个记事本应用程序,我正在create a password弹出一个屏幕,直到您创建一个,然后从那时起log in会弹出一个屏幕。

这是一些示例代码:

File myFile = new File(getFilesDir() + "pass.txt");
if (!myFile.exists()) // if "pass.txt" DOESN'T exist, make them create a password
{ 
    try {

    // this writes the password to the "pass.txt" file 
    // which is the one that is checked to exist.
    // after it is written to, it should always exist.
    FileOutputStream fos = openFileOutput("pass.txt", Context.MODE_PRIVATE);
    fos.write(pass.getBytes());

    // this writes the security question to a different file.
    fos = openFileOutput("securityQ.txt", Context.MODE_PRIVATE);
    fos.write(secQ.getBytes());

    // this writes the security answer to a different file.
    fos = openFileOutput("securityAnswer.txt", Context.MODE_PRIVATE);
    fos.write(secAns.getBytes());

    fos.close();

} catch(Exception e) {}

^ 这是一种方法。然后,在另一个我这样做:

try { // input the right password to the String data
    char[] inputBuffer = new char[1024];
    fIn = openFileInput("pass.txt");
    isr = new InputStreamReader(fIn);
    isr.read(inputBuffer);
    data = new String(inputBuffer);
    isr.close();
    fIn.close();
}catch(IOException e){}

if (password.getText().toString().equals(data)) // if password is right, log in.
{
    loggedin();
}
else // if the password entered is wrong, display the right one.
{
    TextView scr = (TextView)findViewById(R.id.display);
    scr.setText("." + data + "."+'\n'+"." + password.getText().toString() + ".");
}

问题是即使密码输入正确并且显示证明了用户也无法登录。

另一个问题是,每当我再次运行该应用程序时,它都会进入创建屏幕,这意味着它识别出该文件不存在(即使我刚刚写过它)。

我已经处理了整个项目的文件,它可以跟踪输入的文本,这样当你按下一个按钮时,它就会把文件读回给你。即使您关闭它,它也会跟踪您输入的内容。但由于某种原因,密码的东西不起作用。

这是发生了什么的图像(第一个.k.是从文件中读取的数据"pass.txt",第二个.k.是用户String从 输入的数据EditText):

在此处输入图像描述

登录问题的解决方法:

字符串值看起来相同,但彼此不“.equals()”

只好简单地使用.trim()密码用户输入的方法。

4

2 回答 2

2

我将继续评论将密码保存在一个名为“pass.txt”的文件中,并只关注技术部分。

File myFile = new File(getFilesDir() + "pass.txt");

myFile永远不会是一个有效的文件。/路径和文件名之间没有分隔符。由于这永远不会有效,下一行将说它不存在并遍历整个块。

您可以通过以下两种方式轻松解决此问题:

File myFile = new File(getFilesDir() + "/pass.txt");

这只是将分隔符添加到文件名。

File myFile = new File(getFilesDir(), "pass.txt");

这可能是更好的选择,因为它使用显式path, file构造函数。不过,任何一个都很好。

于 2013-07-29T14:41:10.967 回答
0

如果发生,您也可以使用context.openFileInput("pass.txt");并捕获FileNotFoundException,此时您可以“假设”该文件实际上不存在。

于 2013-10-24T17:40:10.937 回答