将文本文件保存到SD卡

13
   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();
           }
       }
   });

我正在尝试将陀螺仪数据保存到文本文件中,但是无法保存。如果有人发现问题,请帮助我纠正它。

5个回答

13

试试这段代码:

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权限


1

你是否已经使用了写入SD卡的权限?

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

0

我是这样做的

public void write() 
{
    FileOutputStream output = null;

    try
    {
        String mediaState = Environment.getExternalStorageState();
        if(mediaState.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
        {
            output = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/download/shared.txt"));

            String str = "Hello, writing to a text file";
            byte[] b = encrypt2(str);
            output.write(b);
        }
        else 
        {
            // error
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            if (output != null)
                output.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

public static byte[] encrypt2(String value)
{
    byte[] input = value.getBytes();
    int nLen = input.length;

    if(nLen % 2 != 0)
    {
        nLen--;
    }

    byte temp;
    for (int i = 0; i < nLen; i += 2)
    {
        temp = input[i+1];
        input[i+1] = input[i];
        input[i] = temp;
    }
    // do encryption
    return Base64.encode(input, Base64.NO_WRAP);
}

同时需要此权限

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

0

试试这个...

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();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = 
                                    new OutputStreamWriter(fOut);
            myOutWriter.append(txtData.getText());
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(),
                    "Done writing SD " + txtData.getText() + ".txt",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
}
   });

同时,在您的清单文件中添加外部存储权限:

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

0

首先在你的androidManifest.xml文件中声明此权限:

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

然后在您的按钮点击事件中编写此代码

 try {
       putStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
        myOutWrite File myFile = new File("/sdcard/SensorData.txt");
        myFile.createNewFile();
        FileOutr.append(txtData.getText());
        myOutWriter.close();
        fOut.close();
        Toast.makeText(v.getContext(),"Done writing SD 'SensorData.txt'", Toast.LENGTH_SHORT).show();
        txtData.setText("");
    } 
    catch (Exception e) 
    {
        Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接