首页 > 解决方案 > 如何在另一个类中调用“写入文件”方法?

问题描述

在我的 Android 应用程序中,我希望有一个类处理所有“写入/读取到文本文件”操作。所以我只需在我的 readUserFile.java 文件中调用我想要的方法。但是我的方法在那个文件中不起作用?

创建文件在我的 MainActivity 中工作正常,但在我的 readUserFile 类中不起作用。我试图使我的 create() 方法静态,但 openFileOutput 将不起作用。我还尝试将 readUserFile 设为自身的静态对象,然后从另一个方法调用 create 方法,但没有成功。Mabye 它有一些我不依赖的上下文要做的事情吗?

public class readUserFile extends Application {

String filename = "users.txt";
boolean exist = false;

public void create(){
    File users = new File(getApplicationContext().getFilesDir(),filename);
    if(!users.exists()){
        String fileContents = "Admin=Admin=99999";
        FileOutputStream outputStream;
        try {
            outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
            outputStream.write(fileContents.getBytes());
            outputStream.close();
            exist = true;
        } catch (Exception e) {
            e.printStackTrace();
            exist = false;
        }
    }
}

public class MainActivity extends AppCompatActivity {

readUserFile userFile = new readUserFile();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    for(int i = 0; i<3; i++){

    if(userFile.exist == true){
        Toast.makeText(this, "!!!FILE EXISTS!!!", Toast.LENGTH_SHORT).show();
    }
    else{
        userFile.create();
        Toast.makeText(this, "File Created "+ i + " "+ userFile.exist, Toast.LENGTH_SHORT).show();
        }
    }
}

我希望它不会那么难,而且应用程序不会在我启动后立即崩溃。

标签: javaandroid

解决方案


您调用 .exist 不正确。使用户对类私有并在 readUserFile 中创建一个返回文件的新方法:

public File getFile()
{
    return users;
}

那么在 MainActivity 你的 if 语句将是:

if(userFile.getFile().exists() == true){
    Toast.makeText(this, "!!!FILE EXISTS!!!", Toast.LENGTH_SHORT).show();
}
else{
    userFile.create();
    Toast.makeText(this, "File Created "+ i + " "+ userFile.getFile().exists(), Toast.LENGTH_SHORT).show();
    }
}

推荐阅读