Saving to SD card as text file(作为文本文件保存到 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 文件,但它没有保存.如果有人发现问题,请帮我纠正.
I am trying to save gyroscope data to txt file but it does not save. If anybody finds the problem, please help to me correct it.
推荐答案
试试这个代码:
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();
        }
    }
另外,请记住在清单文件中包含外部存储权限:
Also, remember to include the external storage permission in your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在 android 6.0 上请求 WRITE_EXTERNAL_STORAGE 的权限
and on android 6.0 to ask for permission for WRITE_EXTERNAL_STORAGE
这篇关于作为文本文件保存到 SD 卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:作为文本文件保存到 SD 卡
				
        
 
            
        - 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
 - 未找到/usr/local/lib 中的库 2022-01-01
 - 获取数字的最后一位 2022-01-01
 - 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
 - 转换 ldap 日期 2022-01-01
 - Eclipse 的最佳 XML 编辑器 2022-01-01
 - GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
 - 如何指定 CORS 的响应标头? 2022-01-01
 - java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
 - 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
 
						
						
						
						
						
				
				
				
				