gpt4 book ai didi

java - 无法在 Android 中读取/写入文件

转载 作者:行者123 更新时间:2023-12-02 06:08:47 27 4
gpt4 key购买 nike

我试图让我的应用程序将文本从 EditText 写入文本文件,然后将其读取到 TextView 中。它之前从未更新过 TextView,现在应用程序崩溃了。任何建议将不胜感激!

public class MainActivity extends Activity implements OnClickListener {

String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";

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

Button rea = (Button) findViewById(R.id.reads1);
rea.setOnClickListener(this);

Button ap = (Button) findViewById(R.id.appends1);
ap.setOnClickListener(this);

}

private void toast(String text)
{
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
toast.show();
}

@SuppressWarnings("resource")
@Override
public void onClick(View v) {

TextView tv=(TextView)findViewById(R.id.textView1);
EditText et=(EditText)findViewById(R.id.editText1);

switch(v.getId()) {
case R.id.reads1:

try
{
FileInputStream fis = new FileInputStream(file);
BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));
String in;
StringBuffer stringBuffer = new StringBuffer();
while ((in = bfr.readLine()) != null) {
stringBuffer.append(in + "\n");
}
tv.setText(stringBuffer.toString());
toast("File successfully loaded.");

}
catch (Exception ex)
{
toast("Error loading file: " + ex.getLocalizedMessage());

}

break;

case R.id.appends1:

String txt=et.getText().toString();

try
{
FileWriter writer = new FileWriter(file);
writer.write(txt);
writer.flush();
writer.close();

toast("File successfully saved.");
}
catch (Exception ex)
{
toast("Error saving file: " + ex.getLocalizedMessage());
}

break;

}

}

}

最佳答案

使用Environment.getExternalStorageDirectory()获取SD卡目录。尝试更改代码中的这一行:

String file = "sdcard/CSCI598.txt";

与:

String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";

此外,正如 @Yahya 提到的,请确保您在 Android list 文件中拥有此权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

如果这不起作用。尝试像这样读取文件:

FileReader fr = new FileReader(file);
BufferedReader inputReader = new BufferedReader(fr);

然后像现在一样使用 while 循环。

像这样编写文件

FileWriter out = new FileWriter(file, true);
out.write(txt + "\n");
out.close();

关于java - 无法在 Android 中读取/写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22058779/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com