Android存储字符串数据到存储字符串数据到txt文件文件
主要为大家详细介绍了Android存储字符串数据到txt文件,具有一定的参考价值,感兴趣的小伙伴们可以参考一
下
需求:需求:
android存储字符串数据简单的有SharePerfence不过只能存储89kb最多的数据(好像),超过这个数据如果不方便网络存
储,只能用文件存储了,这里写了一个工具类,存储到txt文件(不重要的数据,但是体量大)
代码:代码:
1、工具类
package com.xxx.util;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
/**
* 文件工具类
* Created by zst on 2018/2/1.
*/
public class FileUtils {
// 将字符串写入到文本文件中
public static void writeTxtToFile(String strcontent, String filePath, String fileName) {
//生成文件夹之后,再生成文件,不然会出错
makeFilePath(filePath, fileName);
String strFilePath = filePath + fileName;
// 每次写入时,都换行写
String strContent = strcontent + "";
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();
} 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()) {
file.createNewFile();
}
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
//生成文件夹
public static void makeRootDirectory(String filePath) {
File file = null;
评论0