我想在 SD 卡上创建一个文件。在这里我可以创建文件并将其读/写到应用程序,但我在这里想要的是,文件应该保存在 sdcard 的特定文件夹中。我如何使用 FileOutputStream
做到这一点?
// create file
public void createfile(String name)
{
try
{
new FileOutputStream(filename, true).close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// write to file
public void appendToFile(String dataAppend, String nameOfFile) throws IOException
{
fosAppend = openFileOutput(nameOfFile, Context.MODE_APPEND);
fosAppend.write(dataAppend.getBytes());
fosAppend.write(System.getProperty("line.separator").getBytes());
fosAppend.flush();
fosAppend.close();
}
最佳答案
这是我的代码中的一个示例:
try {
String filename = "abc.txt";
File myFile = new File(Environment
.getExternalStorageDirectory(), filename);
if (!myFile.exists())
myFile.createNewFile();
FileOutputStream fos;
byte[] data = string.getBytes();
try {
fos = new FileOutputStream(myFile);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
别忘了:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
关于android - 在android中将文件写入sdcard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20369782/