作为文本文件保存到 SD 卡

本教程将介绍作为文本文件保存到 SD 卡的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

问题描述

stopWriting = (Button) findViewById(R.id.save);
stopWriting.setOnClickListener(new OnClickListener() {

 @SuppressLint("SdCardPath")
 public void onClick(View v) {
  // stop recording the sensor data
  try {

myFile = new File("/sdcard/SensorData/" + txtData.getText() + ".txt");
myFile.createNewFile();

sData = new FileOutputStream(myFile);
myOutWriter = new OutputStreamWriter(sData);
myBufferedWriter = new BufferedWriter(myOutWriter);
myPrintWriter = new PrintWriter(myBufferedWriter);

//if(myFile != null )//stopFlag = mSensorManager.cancelTriggerSensor(null, null);
Toast.makeText(getBaseContext(), "Done", Toast.LENGTH_SHORT).show();
  } catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
  }
 }
});

我正在尝试将陀螺仪数据保存到 txt 文件,但它没有保存.如果有人发现问题,请帮我纠正.

推荐答案

试试这个代码:

public  void writeToFile(String fileName, String body)
 {
  FileOutputStream fos = null;

  try {
final File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/folderName/" );

if (!dir.exists())
{
if(!dir.mkdirs()){
 Log.e("ALERT","could not create the directories");
}
}

final File myFile = new File(dir, fileName + ".txt");

if (!myFile.exists()) 
{ 
 myFile.createNewFile();
} 

fos = new FileOutputStream(myFile);

fos.write(body.getBytes());
fos.close();
  } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
  }
 }

另外,请记住在清单文件中包含外部存储权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

在 android 6.0 上请求 WRITE_EXTERNAL_STORAGE 的权限

好了关于作为文本文件保存到 SD 卡的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。

0
没有账号?注册  忘记密码?