根據網上找到的代碼修改而成,對原作者表示感謝。因爲找不到出處鏈接,此處未標明。使用這個類可以方便的實現將文本信息寫入存儲或者SD卡。整個使用過程只需要兩句代碼。
新建一個class文件 WriteToFile.java
package com.bm.cavell.batterymeasurement.utils;//換成你自己的包名
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
/**
* Created by Cavell on 2018/4/23.
*/
public class WriteToFile {
private static String TAG = "WriteToFile";
private static String filePath = null;
public static void init(Context context,String fileName){
filePath = getFilePath(context) + fileName;//此處傳入的filename 應該是類似 /BlueTooth/record1
}
private static String getFilePath(Context context) {
if (Environment.MEDIA_MOUNTED.equals(Environment.MEDIA_MOUNTED) ||
!Environment.isExternalStorageRemovable()) {//如果外部儲存可用
return context.getExternalFilesDir(null).getPath();//獲得外部存儲路徑,默認路徑爲 /storage/emulated/0/Android/data/com.bm.cavell.batterymeasurement/files/Logs/log_2017-09-14_16-15-09.log
} else {
return context.getFilesDir().getPath();//直接存在/data/data裏,非root手機是看不到的
}
}
public static void writeToFile(String msg) {
if (null == filePath) {
Log.e(TAG, "filePath == null ,未初始化WriteToFile");
return;
}
String text = msg + "\n";//log日誌內容,可以自行定製
//如果父路徑不存在
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();//創建父路徑
}
FileOutputStream fos = null;//FileOutputStream會自動調用底層的close()方法,不用關閉
BufferedWriter bw = null;
try {
fos = new FileOutputStream(filePath + ".txt", true);//這裏的第二個參數代表追加還是覆蓋,true爲追加,flase爲覆蓋
bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close(); //關閉緩衝流
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
調用該類只需要在你的MainActivity中初始化一下即可,如:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WriteToFile.init(getContext(),"/BleData/ble");//初始化,第一句代碼
}
然後在你需要寫內容到SD卡的地方調用
WriteToFile.writeToFile(“你要輸入的內容放在這裏");//第二句代碼