java - 如何在另一个类中调用“写入文件”方法?
问题描述
在我的 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();
}
}
推荐阅读
- c - GtkFileChooserDialog 上的 gtk_widget_destroy 导致分段错误
- python - 为什么我在 Tensorflow 中的逻辑回归分类器没有学习?
- javascript - 如何使用 Jest 测试处理来自外部变量的数据的函数
- http - 如何将来自 HTTPREAD 的数据存储到变量中?
- dns - 用于 Web 配置的正确 CNAME
- r - 如何获得F1、精度、召回和混淆矩阵
- c# - C# 游戏服务器刻度
- snowflake-cloud-data-platform - 向角色添加全局权限时出现问题
- javascript - p元素的Javascript不透明度过渡
- c# - ISet 的命名空间冲突:System.Collections.Generic 和 Iesi.Collections.Generic