Android 讀取本地txt檔案和寫入txt檔案到本地
阿新 • • 發佈:2018-12-06
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<String, String> getFileName(final String fileAbsolutePath) { Map<String, String> 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/"; }