簡體   English   中英

如何在另一個類中調用“寫入文件”方法?

[英]How do I call a "write file" method in another class?

在我的 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();
        }
    }
}

我希望它不會那么難,而且我一啟動應用程序就不會崩潰。

您正在錯誤地調用 .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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2025 STACKOOM.COM