gpt4 book ai didi

java - 以文本文件形式保存到 SD 卡

转载 作者:搜寻专家 更新时间:2023-10-30 19:48:33 26 4
gpt4 key购买 nike

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

此外,请记住在您的 list 文件中包含外部存储权限:

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

在 android 6.0 上请求 WRITE_EXTERNAL_STORAGE 权限

关于java - 以文本文件形式保存到 SD 卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19853401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com