天天看点

【Android】文件读写,读取和写入TXT文件

先申请权限:

看文件是否存在,如果存在,啥也不干;如果不存在,将字符串数据写入到指定文件。

/**
* 如果找不到文件,将数据写入到指定文件
 */
void writeTxtFreq() {
    // 查找文件是否存在
    String freqListTxTPath = Environment.getExternalStorageDirectory() + "/djtest/myfile.txt";
    File file=new File(freqListTxTPath);
    // 如果不存在,创建文件,并写入内容
    if(!file.exists()) {
        Log.i(TAG, "writeTxtFreq: 文件不存在");
		// 获取字符串
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("46000 200 50 2 true\n");
        arrayList.add("46000 300 50 3 true\n");
 		StringBuilder sb = new StringBuilder();
        for (String s : arrayList) {
            sb.append(s);
        }
        // 存储字符串
        FileUtils fileService = new FileUtils();
        String filename = "myfile";
        String pathname = "djtest";
       
        byte[] strByte = sb.toString().getBytes();
        int len = strByte.length;
        fileService.write2PhoneStorageDirectory(getApplicationContext(), GetDir.getDir(pathname), filename + ".txt", strByte, len);
    }
}
           

里面用到的两个方法:

/**
	 * 将运行时数据,写入到手机的存储空间中
	 * @param context	上下文
	 * @param path		路径,不包含文件名,且不包含最后的路径分隔符:djtest
	 * @param fileName 	文件名,带后缀的那种 myfile.txt
	 * @param data		待保存的字符串数据,转换成byte数组后使用
	 * @param len		byte数组长度
	 * @return			返回File
	 */
	public static File write2PhoneStorageDirectory(Context context, String path, String fileName, byte[] data, int len) {
		File file = null;
		OutputStream output = null;
		try {
			file = createSDFile(path + "/" + fileName);
			output = new FileOutputStream(file, false);
			byte buffer[] = new byte[len];
			System.arraycopy(data, 0, buffer, 0, len);
			output.write(buffer);
			output.flush();

			Uri uri = Uri.fromFile(file);
			Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
			context.sendBroadcast(intent);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null)
					output.close();
				else
					Log.v(TAG, "output null");

			} catch (IOException e) {

				e.printStackTrace();
			}
		}
		return file;
	}
           
public class GetDir {
    public static String getDir(String pathname) {
        String path = Environment.getExternalStorageDirectory().toString();
        File dir = new File(path + File.separator + pathname);
        if (dir.exists()) {
            return dir.toString();
        } else {
            dir.mkdirs();
            return dir.toString();
        }
    }
}
           
public String createDir(String path) {
    File dir = new File(path);
    if (dir.exists()) {
        return dir.toString();
    } else {
        dir.mkdirs();
        return dir.toString();
    }
}
           

读取文件

/**
 * 从TXT文件中逐行读取数据,作为字符串,添加到Constant.list_freq_from_file列表中
 */
void readFromTxt() {
    // 读取文件 在小米9SE中:/storage/emulated/0/djtest/WifiList.txt
    String freqListTxTPath = Environment.getExternalStorageDirectory() + "/djtest/earfcn.txt";
    ArrayList<String> FreqList = FileUtils.readTxtFileIntoStringArrList(freqListTxTPath);
}
           

用到的函数工具:

/**
 * 功能:Java读取txt文件的内容
 * 步骤:
 * 1:先获得文件句柄
 * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
 * 3:读取到输入流后,需要读取生成字节流
 * 4:一行一行的输出  readline()
 * 备注:需要考虑的是异常情况
 *
 * @param filePath
 *            文件路径[到达文件:如: D:\aa.txt]
 * @return 将这个文件按照每一行切割成数组存放到list中。
 */
public static ArrayList<String> readTxtFileIntoStringArrList(String filePath)
{
	ArrayList<String> list = new ArrayList<>();
	try
	{
		String encoding = "GBK";
		File file = new File(filePath);
		if (file.isFile() && file.exists())
		{
			// 判断文件是否存在
			InputStreamReader read = new InputStreamReader(
					new FileInputStream(file), encoding);  // 考虑到编码格式
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;

			while ((lineTxt = bufferedReader.readLine()) != null)
			{
				list.add(lineTxt);
			}
			bufferedReader.close();
			read.close();
		}
		else
		{
			Log.i(TAG, "找不到指定的文件");
		}
	}
	catch (Exception e)
	{
		Log.i(TAG, "读取文件内容出错");
		e.printStackTrace();
	}

	return list;
}
           

读取:另外的不需要任何编码格式设定的:

public static int readTextFromFile(String pathName) {
    File myfile = new File(pathName);
    if (myfile.exists()) {
        try {
            FileInputStream fis = new FileInputStream(myfile);
            InputStreamReader inputStreamReader;
            inputStreamReader = new InputStreamReader(fis); // 无需设置编码格式
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line;
            Log.i(TAG, "readTextFromFile: 平台默认编码格式:" + Charset.defaultCharset());
            while (((line = reader.readLine()) != null)) {
                Log.i(TAG, "readTextFromFile:" + line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        return 0;
    }
    return 1;
}