我正在开发一个Android应用程序,它将在安装到手机上的SD卡上创建一个新的.txt
文件。我是android编程的新手,但我写了这段代码。然后我在真正的手机(不是模拟器)上测试了应用程序。我导航到我的文件>所有文件> SD存储卡和应该创建的文件不在那里。
我做错了什么以及如何解决我的错误?提前谢谢!
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String filename = "filename.txt";
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos;
byte[] data = new String("data to write to file").getBytes();
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
更新!!!
我发现由于某种原因在手机内存中创建的文件。为什么会发生这种情况以及如何在存储卡中创建它们呢?
答案 0 :(得分:0)
File extDir = getExternalFilesDir(null);
String path = extDir.getAbsolutePath();
File file = new File(extDir, "filename.txt");
if(checkExternalStorage()){
String text ="writing into externanal storage";
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
fos.write(text.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean checkExternalStorage() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
return true;
}
return false;
}
答案 1 :(得分:0)
好的,我认为你想要这个代码......
File sd = Environment.getExternalStorageDirectory();
File f = new File(sd.getAbsolutePath(), filename);
OutputStreamWriter fout = new OutputStreamWriter(new FileOutputStream(f));
fout.write("this is a test.");
fout.close();
我希望它有效!
答案 2 :(得分:0)
要访问实际的SD卡,请使用:
String path = Syst.env("SECONDARY_STORAGE");