Save the file in android to the sdcard code instance
- 2020-06-19 11:44:48
- OfStack
Direct code:
package com.example.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// The file name and file contents to save
String fileName = "test.txt";
String content = "This is a test.";
// judge sdcard If there is a
String state = Environment.getExternalStorageState();
if(state.equals(Environment.MEDIA_MOUNTED)) {
// To obtain SDCard directory
File sdcardPath = Environment.getExternalStorageDirectory();
File file = new File(sdcardPath, fileName);
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this, " Save success ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "sdcard There is no fetch that cannot be written ", Toast.LENGTH_SHORT).show();
}
}
}