AndroidManifest.xml文件加入权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
android 9以上还需要加入requestLegacyExternalStorage
<application
android:requestLegacyExternalStorage="true"
.......
-
动态权限申请
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 1000)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//同意申请权限
} else
{
// 用户拒绝申请权限
Toast.makeText(BlinkyActivity.this,"请同意写操作来记录心率原始数据", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
-
onCreate中调用
if (ContextCompat.checkSelfPermission(BlinkyActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager. PERMISSION_GRANTED) {
ActivityCompat. requestPermissions( this, new String[]{Manifest.permission. WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE },
1000);
}
-
文件读写工具类
package no.nordicsemi.android.debug.utils;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
public class FileUtils {
// 将字符串写入到文本文件
public static void writeTxtToFile(String strcontent, String filePath, String fileName) {
makeFilePath(filePath, fileName);
String strFilePath = filePath +File.separator+ fileName;
String strContent = strcontent + "\r\n";
try {
File file = new File(strFilePath);
if (!file.exists()) {
Log.d("TestFile", "Create the file:" + strFilePath);
File parent_file = file.getParentFile();
if(parent_file != null){
if(parent_file.mkdirs())
{
Log.d("TestFile", "parent file path:" + parent_file.getPath());
}
}
if(!file.createNewFile())
{
Log.d("TestFile", "文件已经存在,不需要创建");
}
}
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(file.length());
raf.write(strContent.getBytes());
raf.close();
} catch (Exception e) {
Log.e("TestFile", "Error on write File:" + e);
}
}
//生成文件
public static File makeFilePath(String filePath, String fileName) {
File file = null;
makeRootDirectory(filePath);
try {
file = new File(filePath + fileName);
if (!file.exists()) {
if(!file.createNewFile())
{
Log.d("TestFile", "文件已经存在,不需要创建");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
//生成文件夹
public static void makeRootDirectory(String filePath) {
File file = null;
try {
file = new File(filePath);
if (!file.exists()) {
if(file.mkdir()){
Log.d("TestFile", "file path:" + file.getPath());
}
}
} catch (Exception e) {
Log.i("error:", e + "");
}
}
//读取指定目录下的所有TXT文件的文件内容
public static String getFileContent(File file) {
String content = "";
if (!file.isDirectory()) { //检查此路径名的文件是否是一个目录(文件夹)
if (file.getName().endsWith("txt")) {//文件格式为""文件
try {
InputStream instream = new FileInputStream(file);
InputStreamReader inputreader
= new InputStreamReader(instream, StandardCharsets.UTF_8);
BufferedReader buffreader = new BufferedReader(inputreader);
String line = "";
//分行读取
while ((line = buffreader.readLine()) != null) {
content += line + "\n";
}
instream.close();//关闭输入流
} catch (java.io.FileNotFoundException e) {
Log.d("TestFile", "The File doesn't not exist.");
} catch (IOException e) {
Log.d("TestFile", Objects.requireNonNull(e.getMessage()));
}
}
}
return content;
}
}
-
测试写入文件
String temp = "This is a test file";
File file = getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS);
FileUtils.writeTxtToFile(temp, file.getPath(), "test.txt");