gpt4 book ai didi

java - Android模拟器中的问题写入文件问题

转载 作者:行者123 更新时间:2023-11-29 04:00:07 26 4
gpt4 key购买 nike

我正在尝试使用以下代码将一些简单数据写入外部存储。我在这里遗漏了一些东西,但不确定是什么。谢谢

罗布达

public class TimeCard extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final Button button = (Button) findViewById(R.id.Button01);
final EditText edittext = (EditText) findViewById(R.id.EditText01);
final EditText edittext1 = (EditText)findViewById(R.id.EditText02);
final EditText edittext2 = (EditText)findViewById(R.id.EditText03);
final EditText edittext3 = (EditText)findViewById(R.id.EditText04);
final String inputString = edittext + "/n" + edittext1 + "/n"+ edittext2 + "/n" + edittext3;
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Do it
CreateFile(inputString);
//Let them know it
Toast.makeText(TimeCard.this, "You are Clocked In", Toast.LENGTH_LONG).show();
}


});
}
//Write to SD Card
public void CreateFile(String InputString){

File SDCard = Environment.getExternalStorageDirectory();
String FILENAME = SDCard + "/time_card.txt";

FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {

e.printStackTrace();
}
try {
fos.write(InputString.getBytes());
} catch (IOException e) {

e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {

e.printStackTrace();
}
}
}

最佳答案

我尝试运行您的代码,错误是由您使用openFileOutput(String name, int mode) 方法的方式引起的。查看 LogCat 内部,我可以看到以下异常:

java.lang.IllegalArgumentException: File /mnt/sdcard/time_card.txt contains a path separator

这为我指出了 this question 的答案方向,这也可能会解决您的问题:

Context.openFileOutput is meant to be used for creating files private to your application. They go in your app's private data directory. You supply a name, not a path

documentation for openFileOutput还指出了有关函数的名称参数的信息:

The name of the file to open; can not contain path separators.

为了将来引用,当您遇到此类问题时,学习如何使用您可用的工具(例如 LogCat)是绝对重要的。没有它们,您将很难找出问题所在。因此,我建议您阅读一些有关如何执行此操作的信息。

关于java - Android模拟器中的问题写入文件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4145302/

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