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

4

我正在制作一个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
}
}
}       
}
}

你有什么问题吗? - stefan
为什么人们总是把一堆代码扔在那里,然后认为别人会读懂它?我的意思是,为什么你不能只给我们那些有问题的相关代码呢? - ariefbayu
我需要知道如何从文本框编写文本文件到SD卡。 - MySoftware
2个回答

7
以下代码可以帮助您将文本写入文件并保存到根目录:
首先从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 权限。


什么是文件?我在它下面得到了这个错误信息:文件无法解析为变量。这是在新的FileWriter之后。 - MySoftware

1
这是一些基本代码,可以将TextView中的文本写入您SD卡上的文件。
File myFile = new File(Environment.getExternalStorageDirectory().toString(), "myFile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();

希望这能帮到你!


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