一个文件操作的小Demo。如图:
写一个文件工具类:
import android.text.TextUtils;
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.text.DecimalFormat;
public class FileUtils {
private static String TAG = "FileUtils";
/**
* 将字符串写入到文本文件中
* @param strcontent
* @param filePath
* @param fileName
*/
public static void writeTxtToFile(String strcontent, String filePath, String fileName) {
makeFilePath(filePath, fileName);
String strFilePath = filePath + fileName;
String strContent = strcontent + "\r\n";
try {
File file = new File(strFilePath);
if (!file.exists()) {
Log.d(TAG, "Create the file:" + strFilePath);
file.getParentFile().mkdirs();
file.createNewFile();
}
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(file.length());
raf.write(strContent.getBytes());
raf.close();
} catch (Exception e) {
Log.e(TAG, "Error on write File:" + e);
}
}
/**
* 创建文件
* @param filePath
* @param fileName
* @return
*/
public static File makeFilePath(String filePath, String fileName) {
File file = null;
makeRootDirectory(filePath);
try {
file = new File(filePath + fileName);
if (!file.exists()) {
file.createNewFile();
}
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
/**
* 创建文件目录
*
* @param filePath
*/
public static void makeRootDirectory(String filePath) {
File file = null;
try {
file = new File(filePath);
if (!file.exists()) {
file.mkdir();
}
} catch (Exception e) {
Log.i("error:", e + "");
}
}
/**
* 读取文件
*
* @param strFilePath
* @return
*/
public static String ReadTxtFile(String strFilePath) {
String path = strFilePath;
String content = "";
File file = new File(path);
if (file.isDirectory()) {
Log.d("TestFile", "The File doesn't not exist.");
} else {
try {
InputStream instream = new FileInputStream(file);
if (instream != null) {
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
while ((line = buffreader.readLine()) != null) {
content += line + "\n";
}
instream.close();
}
} catch (java.io.FileNotFoundException e) {
Log.d(TAG, "The File doesn't not exist.");
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
return content;
}
/**
* 删除文件
*
* @param path
* @return
*/
public static boolean delete(String path) {
Log.i(TAG, "delete2:" + path);
if (TextUtils.isEmpty(path)) {
return false;
}
Log.i(TAG, "delete3:" + path);
File file = new File(path);
Log.i(TAG, "file.exists():" + file.exists());
if (file.exists()) {
try {
Log.i(TAG, "file.isFile():" + file.isFile());
if (file.isFile()) {
Log.i(TAG, "delete file.isFile():true");
return deleteFile(path);
} else {
return deleteDirectory(path);
}
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
return false;
}
}
return false;
}
/**
* 删除单个文件
*
* @param path
* @return
*/
public static boolean deleteFile(String path) {
File file = new File(path);
Log.i(TAG, "delete deleteFile:path:" + path);
if (file.exists() && file.isFile()) {
boolean b = file.delete();
Log.i(TAG, "deleteFile:" + b);
return b;
} else {
return false;
}
}
/**
* 删除目录及目录下的文件
*
* @param dir 要删除的目录的文件路径
* @return 目录删除成功返回true,否则返回false
*/
private static boolean deleteDirectory(String dir) {
if (!dir.endsWith(File.separator))
dir = dir + File.separator;
File dirFile = new File(dir);
if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
return false;
}
boolean flag = true;
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag)
break;
} else if (files[i].isDirectory()) {
flag = deleteDirectory(files[i]
.getAbsolutePath());
if (!flag)
break;
}
}
if (!flag) {
return false;
}
return dirFile.delete();
}
/**
* 获取指定文件大小
* @param
* @return
* @throws Exception
*/
public static long getFileSize(File file) throws Exception {
long size = 0;
if (file.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(file);
size = fis.available();
} else {
file.createNewFile();
}
return size;
}
/**
* 获取指定文件夹
* @param
* @return
* @throws Exception
*
*/
public static long getFileSizes(File f) throws Exception {
long size = 0;
File flist[] = f.listFiles();
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getFileSizes(flist[i]);
} else {
size = size + getFileSize(flist[i]);
}
}
return size;
}
/**
* 转换文件大小
* @param fileS
* @return
*
*/
public static String FormetFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
String wrongSize = "0B";
if (fileS == 0) {
return wrongSize;
}
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "KB";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "MB";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "GB";
}
return fileSizeString;
}
}
在MainActivity调用:
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static String TAG = "MainActivity";
private Button mWriteFile;
private Button mReadFile;
private Button mDeleteFile;
private EditText mEditText;
private TextView mTvShow;
private String filePatch = "/storage/sdcard0/test/test.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView(){
mWriteFile = findViewById(R.id.button_write);
mEditText = findViewById(R.id.et_text);
mTvShow = findViewById(R.id.tv_read);
mReadFile = findViewById(R.id.button_read);
mDeleteFile = findViewById(R.id.button_delete);
mWriteFile.setOnClickListener(this);
mDeleteFile.setOnClickListener(this);
mReadFile.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_read:
String text = FileUtils.ReadTxtFile(filePatch);
if (!TextUtils.isEmpty(text)) {
mTvShow.setText(text);
}else {
mTvShow.setText(null);
}
break;
case R.id.button_write:
if (mEditText.getText() != null) {
String packName = mEditText.getText().toString();
initData(packName);
mEditText.setText("");
}
break;
case R.id.button_delete:
if (!TextUtils.isEmpty(filePatch)) {
FileUtils.delete(filePatch);
mTvShow.setText(null);
}
break;
default:
break;
}
}
private void initData(String str) {
String filePath = "/sdcard/test/";
String fileName = "test.txt";
FileUtils.writeTxtToFile(str, filePath, fileName);
}
@Override
protected void onResume() {
super.onResume();
if (!TextUtils.isEmpty(filePatch)) {
String text = FileUtils.ReadTxtFile(filePatch);
if (!TextUtils.isEmpty(text)) {
mTvShow.setText(text);
} else {
mTvShow.setText(null);
}
}
/*判断文件大小,超过就删除*/
File file = new File(filePatch);
if(file.exists()) {
try {
Long size = FileUtils.getFileSize(file);
Log.d(TAG, "size == " + FileUtils.FormetFileSize(size));
if(size >= 1024){
FileUtils.delete(filePatch);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
附上布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/et_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:hint="输入应用包名"/>
<Button
android:id="@+id/button_write"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:clickable="true"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:text="写入"
/>
<Button
android:id="@+id/button_delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:clickable="true"
android:layout_margin="20dip"
android:text="删除"
/>
<Button
android:id="@+id/button_read"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:clickable="true"
android:layout_margin="20dip"
android:text="读取"
/>
<TextView
android:id="@+id/tv_read"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dip"/>
</LinearLayout>
还有在AndroidManifest.xml里面加上权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>