Problem Writing Files problem in Android Emulator
I am trying to write some simple data to External storage using the following code. I am missing something here but not sure what. Thanks
RobD
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();
}
}
}
I tried running your code, and the error is caused by the way you use the openFileOutput(String name, int mode)
method. Looking inside LogCat, I can see the following exception:
java.lang.IllegalArgumentException: File /mnt/sdcard/time_card.txt contains a path separator
This pointed me in the direction of the answer to this question, which will probably solve your problem as well:
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
The documentation for openFileOutput also indicates this about the name parameter of the function:
The name of the file to open; can not contain path separators.
For future references, when you experience problems like this, it is absolutely vital that you learn how to use the tools available to you, such as LogCat. Without them, you'll have a hard time figuring out what is wrong. So I recommend reading up a bit on how to do this.
It is hard to tell when you don't show what kind of error message you get. But my first guess is that you have forgotten to include the WRITE_EXTERNAL_STORAGE
permission in your AndroidManifest.xml file.
上一篇: 错误StrictMode $ AndroidBlockGuardPolicy.onNetwork
下一篇: Android模拟器中的问题写入文件问题