ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

在Android中写入和从SD卡读取文件

2019-06-10 02:32:58  阅读:248  来源: 互联网

标签:android storage android-sdcard


我正在制作一个Android应用程序,一旦按下按钮,一旦收到包含相同文本的SMS消息,就会从textview将文本文件写入SD卡.

收到短信后,如何将文本文件保存到SD卡并从该文本文件中读取?这是我到目前为止的代码:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
import android.media.MediaPlayer;

public class IncomingSmsCaptureApp extends BroadcastReceiver {
MediaPlayer mp1;
@Override
public void onReceive(Context context, Intent intent) {
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"Notes\file.txt");

//Read text from file
String text = new String();

try {
  BufferedReader br = new BufferedReader(new FileReader(file));
  String line;

  while ((line = br.readLine()) != null) {
  }
}
catch (IOException e) {
  //You'll need to add proper error handling here
}
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();       
SmsMessage[] msgs = null;
String str = "";     
String Message = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];           
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);               
str += "SMS from " + msgs[i].getOriginatingAddress();                    
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";       
Message = msgs[i].getMessageBody().toString();
}
//---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
if (Message.equals("alarm")) {
//Play alarm sound
mp1 = MediaPlayer.create(context, R.raw.alarm);
mp1.start();
}
else {
if (Message.equals(text)) {
    //Perform action
}
}
}       
}
}

解决方法:

以下代码将帮助您将文本写入文件并将其保存在根目录中

首先从textview获取文本

String text = myTextView.getText().toString();

然后编写以下语句以写入文本文件

File logFile = new File(Environment.getExternalStorageDirectory().toString(), "myFile.txt");
if(!logFile.exists()) {
     logFile.createNewFile();
}

BufferedWriter output = new BufferedWriter(new FileWriter(logFile));
output.write(text);
output.close();

您的文件将存储在根目录中

别忘了在清单中添加WRITE_EXTERNAL_STORAGE权限

标签:android,storage,android-sdcard
来源: https://codeday.me/bug/20190610/1208799.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有