文件操作需要手机权限,需要在AndroidManifest.xml
添加
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
ActivityCompat.requestPermissions(MainActivity.this, permissions, 10);
//return;
}
}
// 获取权限回调
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 10) {
Log.e("kostal", "grantResults = " + grantResults.toString() + "permissions=" + permissions);
for (int i = 0; i < permissions.length; i++) {
Log.e("kostal", "i = " + i + " " + permissions[i]);
}
}
}
--------------------------------第一种方式------------------------------------------
1、获取文件路径
/**
* 获取文件路径
* filePath=/storage/emulated/0/Android/data/com.example.wifiapplication/files/20120101_100216_log.txt
* */
public String getFilesPath(Context context) {
// 20120101_100216_log.txt 用时间格式创建文件名
Calendar c = Calendar.getInstance();
SimpleDateFormat fdate = new SimpleDateFormat("yyyyMMdd_HHmmss");
String fname = fdate.format(c.getTime()) + "_log.txt";
String filePath ;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
//外部存储可用
filePath = context.getExternalFilesDir(null).getPath() + "/" + fname;
} else {
//外部存储不可用
filePath = context.getFilesDir().getPath() + "/" + fname;
}
return filePath;
}
2、写入数据
try {
FileOutputStream outputStream = new FileOutputStream(filePath, true);// true 为 追加写入,false 为删除写入(把之前的数据清除掉,再写入)
outputStream.write("88888".getBytes());
outputStream.write("99999999".getBytes());
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
3、读取数据
try {
FileInputStream inputStream = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int hasRead = inputStream.read(buffer);
StringBuilder sb = new StringBuilder();
sb.append(new String(buffer, 0, hasRead));
Log.e("wyy", "读取数据=" + sb.toString());
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
--------------------------------第二种方式------------------------------------------
1、获取名称
/**
* 获取文件名称
* */
private String getFileName(){
Calendar c = Calendar.getInstance();
SimpleDateFormat fdate = new SimpleDateFormat("yyyyMMdd_HHmmss");
return fdate.format(c.getTime()) + "_log.txt";
}
2、写入数据
try {
FileOutputStream outputStream = FileHandleActivity.this.openFileOutput(getFileName(),Context.MODE_APPEND);
outputStream.write("需要写入的数据".getBytes());
outputStream.close();// 关闭文件
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
3、读取数据
try {
FileInputStream inputStream = this.openFileInput(fname);
byte[] buffer = new byte[1024];
int hasRead = inputStream.read(buffer);
StringBuilder sb = new StringBuilder();
sb.append(new String(buffer, 0, hasRead));
Log.e("wyy", "读取数据=" + sb.toString());
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
【注意】第一种方法和第二种方法的区别:
1.文件路径不一样
2.第一种方法可能对API要求比较高,亲测在minSdkVersion 19
/ targetSdkVersion 29
上是没有问题。但是不保证在你的手机上没有问题。具体情况具体分析。
--------------------------------第三种方式(常用)----------------------------------------
新建
FileHandlerClass
类,进行文件夹创建,然后再写入数据。
文件可以在文件管理中找到,并可以导出。
public class FileHandlerClass {
/**
* 文件夹路径
*/
private static final String fileDirPath = "/sdcard/AKOSTAL";
/**
* 文件名
*/
private static final String fileName = "logInfo.csv";
/**
* 将数据存到文件中
*
* @param context context
* @param data 需要保存的数据
* @param fileName 文件名
*/
public static void saveDataToFile(Context context, String data, String fileName) {
File filesDir = context.getFilesDir();
// 动态获得路径
File file = new File(filesDir, "qqlogin.txt");
// 输出流,把数据输出到文件中
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
// 写入字节流
fos.write(data.getBytes());
// 清空缓存
fos.flush();
// 关闭流
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fileOutputStream = null;
BufferedWriter bufferedWriter = null;
try {
/**
* "data"为文件名,MODE_PRIVATE表示如果存在同名文件则覆盖,
* 还有一个MODE_APPEND表示如果存在同名文件则会往里面追加内容
*/
fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
bufferedWriter.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter != null) {
bufferedWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 从文件中读取数据
*
* @param context context
* @param fileName 文件名
* @return 从文件中读取的数据
*/
public static String loadDataFromFile(Context context, String fileName) {
FileInputStream fileInputStream = null;
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
/**
* 注意这里的fileName不要用绝对路径,只需要文件名就可以了,系统会自动到data目录下去加载这个文件
*/
fileInputStream = context.openFileInput(fileName);
bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
String result = "";
while ((result = bufferedReader.readLine()) != null) {
stringBuilder.append(result);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return stringBuilder.toString();
}
/**
* 把文件存储在内部,不可以导出
**/
public static void writeTheftDate(Context context, String msg) {
// 步骤1:获取输入值
if (msg == null) return;
try {
// 步骤2:创建一个FileOutputStream对象,MODE_APPEND追加模式
FileOutputStream fos = context.openFileOutput("theftdatefile.txt", context.MODE_APPEND);
// 步骤3:将获取过来的值放入文件
fos.write(msg.getBytes());
// 步骤4:关闭数据流
fos.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
// 读取数据
public String readTheftDate(Context context) {
try {
FileInputStream inStream = context.openFileInput("theftdatefile.txt");
byte[] buffer = new byte[1024];
int hasRead = 0;
StringBuilder sb = new StringBuilder();
while ((hasRead = inStream.read(buffer)) != -1) {
sb.append(new String(buffer, 0, hasRead));
}
inStream.close();
return sb.toString();
} catch (Exception e) {
//e.printStackTrace();
}
return null;
}
/**
* 把文件存储在外部,可以导出
**/
public static void KKCreateFilePath(String str) {
//先实例化一个file对象,参数为路径名
File file = new File(fileDirPath + "/" + fileName);
try {
if (file.exists()) { // 已经存在 直接写入文件
FileWriter write = new FileWriter(file, true);
BufferedWriter bufferedWriter = new BufferedWriter(write);
bufferedWriter.write(str);
bufferedWriter.newLine();//换行
bufferedWriter.flush();
write.close();
bufferedWriter.close();
} else {
file = new File(fileDirPath);
file.mkdir();// 创建文件夹
file = new File(fileDirPath + "/" + fileName);
file.createNewFile();//创建文件
// 写入文件
FileWriter write = new FileWriter(file, true);
BufferedWriter bufferedWriter = new BufferedWriter(write);
bufferedWriter.write(str);
bufferedWriter.newLine();//换行
bufferedWriter.flush();
write.close();
bufferedWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
如何使用
使用案例
FileHandlerClass.KKCreateFilePath( "1,2,3,4,5,6");
FileHandlerClass.KKCreateFilePath( "88,55,66,77,99,1000");