Android 读取本地txt文件和写入txt文件到本地

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;

/**
 * created by Administrator on 2018/8/28 19:37
 */
public class SaveDeviceMessageInfo {

    public static String fileName = "id.txt";//保存设备ID
    public static String rateName = "rate.txt";//保存设备收费标准

    /**
     * 保存设备ID
     *
     * @param deviceId 输入的设备ID
     */
    public static boolean saveDeviceId(String deviceId) {
        File file = new File(Constant.PATH_SAVE_DEVICE + fileName);
        if (file.exists()) {
            FileUtil.delete(Constant.PATH_SAVE_DEVICE + fileName);
        }
        return writeTxtToFile(Base64Util.encode(deviceId), Constant.PATH_SAVE_DEVICE, fileName);//对保存的设备ID加密保存
    }

    /**
     * 保存收费标准
     *
     * @param rate 输入的收费标准
     */
    public static boolean saveRate(String rate) {
        File file = new File(Constant.PATH_RATE + rateName);
        if (file.exists()) {
            FileUtil.delete(Constant.PATH_RATE + rateName);
        }
        return writeTxtToFile(rate, Constant.PATH_RATE, rateName);//对保存的收费标准
    }

    /**
     * 字符串写入本地txt
     *
     * @param strcontent 文件内容
     * @param filePath   文件地址
     * @param fileName   文件名
     * @return 写入结果
     */
    private static boolean writeTxtToFile(String strcontent, String filePath, String fileName) {
        boolean isSavaFile = false;
        makeFilePath(filePath, fileName);
        String strFilePath = filePath + fileName;
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "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();
            isSavaFile = true;
        } catch (Exception e) {
            isSavaFile = false;
            Log.e("TestFile", "Error on write File:" + e);
        }
        return isSavaFile;
    }

    /**
     * 生成文件
     *
     * @param filePath 文件地址
     * @param fileName 文件名
     */
    private 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;
    }

    /**
     * 生成文件夹
     */
    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 + "");
        }
    }

    /**
     * 读取本地文件
     */
    public static String readDeviceId() {
        String path = Constant.PATH_SAVE_DEVICE + fileName;
        StringBuilder stringBuilder = new StringBuilder();
        File file = new File(path);
        if (!file.exists()) {
            return "";
        }
        if (file.isDirectory()) {
            Log.e("TestFile", "The File doesn't not exist.");
            return "";
        } 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) {
                        stringBuilder.append(line);
                    }
                    instream.close();
                }
            } catch (java.io.FileNotFoundException e) {
                Log.e("TestFile", "The File doesn't not exist.");
                return "";
            } catch (IOException e) {
                Log.e("TestFile", e.getMessage());
                return "";
            }
        }
        return Base64Util.decode(stringBuilder.toString());//对读到的设备ID解密
    }

    /**
     * 读取本地文件
     */
    public static String readRate() {
        String path = Constant.PATH_RATE + rateName;
        StringBuilder stringBuilder = new StringBuilder();
        File file = new File(path);
        if (!file.exists()) {
            return "";
        }
        if (file.isDirectory()) {
            Log.e("TestFile", "The File doesn't not exist.");
            return "";
        } 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) {
                        stringBuilder.append(line);
                    }
                    instream.close();
                }
            } catch (java.io.FileNotFoundException e) {
                Log.e("TestFile", "The File doesn't not exist.");
                return "";
            } catch (IOException e) {
                Log.e("TestFile", e.getMessage());
                return "";
            }
        }
        return stringBuilder.toString();//对读到的设备ID解密
    }
}

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class FileUtil {

    /**
     * 遍历所有文件
     *
     * @param fileAbsolutePath 传入的文件的父目录
     */
    public static Map getFileName(final String fileAbsolutePath) {
        Map map = new HashMap<>();
        File file = new File(fileAbsolutePath);
        File[] subFile = file.listFiles();
        try {
            if (subFile.length > 0) {
                for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
                    // 判断是否为文件夹
                    if (!subFile[iFileLength].isDirectory()) {
                        String filename = subFile[iFileLength].getName();
                        map.put(String.valueOf(iFileLength), filename);
                    }
                }
            }
        } catch (NullPointerException e) {
            e.toString();
        }
        return map;
    }

    /**
     * 读取日志文件
     *
     * @param file 本地txt或log文件
     * @return 返回读取到的文件内容
     */
    public static String getFileContent(File file) {
        String content = null;
        try {
            InputStream is = new FileInputStream(file);
            InputStreamReader reader = new InputStreamReader(is);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                content = content + line + "\n";
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.toString();
        }
        return content;
    }

    /**
     * 删除文件,可以是文件或文件夹
     *
     * @param fileName 要删除的文件名
     * @return 删除成功返回true,否则返回false
     */
    public static boolean delete(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            System.out.println("删除文件失败:" + fileName + "不存在!");
            return false;
        } else {
            if (file.isFile())
                return deleteFile(fileName);
            else
                return deleteDirectory(fileName);
        }
    }

    /**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName.replaceAll(" ", ""));
        LogUtils.e("TAG", "fileName:" + fileName);
        LogUtils.e("TAG", "file.isFile():" + file.isFile());
        if (file.isFile() || file.exists()) {
            boolean isDel = file.delete();
            return isDel;
        } else {
            LogUtils.e("MainActivity", "删除单个文件失败:" + fileName + "不存在!");
            return false;
        }
    }

    /**
     * 删除目录及目录下的文件
     *
     * @param dir 要删除的目录的文件路径
     * @return 目录删除成功返回true,否则返回false
     */
    public static boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾,自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除目录失败:" + dir + "不存在!");
            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) {
            System.out.println("删除目录失败!");
            return false;
        }
        if (dirFile.delete()) {
            System.out.println("删除目录" + dir + "成功!");
            return true;
        } else {
            return false;
        }
    }
}

import android.os.Environment;
import java.io.File;

/**
 * Created by Administrator on 2018/10/18.
 */
public class Constant {

    /**
     * 设备ID保存地址
     */
    public static String PATH_SAVE_DEVICE = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator + "deviceId/";

    /**
     * 收费标准存放地址
     * */
    public static String PATH_RATE = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator + "rate/";

}

 

你可能感兴趣的:(Android)