最近有这样的需求,把每次统计到的数据,以txt形式保存到手机SD卡或是手机内存中,遇到一些问题,记录下来。


首先如果要在程序中使用sdcard进行存储,我们必须要在AndroidManifset.xml文件进行下面的权限设置:

 <!-- SDCard中创建与删除文件权限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><!-- 向SDCard写入数据权限 --><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

接着在使用SDcard进行读写的时候 会用到Environment类下面的几个静态方法 :

1: getDataDirectory() 获取到Android中的data数据目录(sd卡中的data文件夹)
2:getDownloadCacheDirectory() 获取到下载的缓存目录(sd卡中的download文件夹)
3:getExternalStorageDirectory() 获取到外部存储的目录 一般指SDcard(/storage/sdcard0)
4:getExternalStorageState() 获取外部设置的当前状态 一般指SDcard,比较常用的应该是MEDIA_MOUNTED(SDcard存在并且可以进行读写)还有其他的一些状态,可以在文档中进行查找。

5:getRootDirectory() 获取到Android Root路径


好,以下是具体操作,直接看代码:

1,判断SD卡是否存在

/** * 判断SDCard是否存在 [当没有外挂SD卡时,内置ROM也被识别为存在sd卡] *  * @return */public static boolean isSdCardExist() {return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);}

2,获取SD卡根目录

/** * 获取SD卡根目录路径 *  * @return */public static String getSdCardPath() {boolean exist = isSdCardExist();String sdpath = "";if (exist) {sdpath = Environment.getExternalStorageDirectory().getAbsolutePath();} else {sdpath = "不适用";}return sdpath;}

3,获取默认的文件存放路径

/** * 获取默认的文件路径 *  * @return */public static String getDefaultFilePath() {String filepath = "";File file = new File(Environment.getExternalStorageDirectory(),"abc.txt");if (file.exists()) {filepath = file.getAbsolutePath();} else {filepath = "不适用";}return filepath;}

4-1,使用FileInputStream读取文件

        try {    File file = new File(Environment.getExternalStorageDirectory(),    "test.txt");            FileInputStream is = new FileInputStream(file);            byte[] b = new byte[inputStream.available()];            is.read(b);            String result = new String(b);            System.out.println("读取成功:"+result);        } catch (Exception e) {        e.printStackTrace();        }

4-2,使用BufferReader读取文件

try {File file = new File(Environment.getExternalStorageDirectory(),DEFAULT_FILENAME);BufferedReader br = new BufferedReader(new FileReader(file));String readline = "";StringBuffer sb = new StringBuffer();while ((readline = br.readLine()) != null) {System.out.println("readline:" + readline);sb.append(readline);}br.close();System.out.println("读取成功:" + sb.toString());} catch (Exception e) {e.printStackTrace();}

httpConnection读取流保存成String数据

URL url = new URL(getForwardUrl("/queryUserByUNorIP"));HttpURLConnection conn = (HttpURLConnection) url.openConnection();InputStream is = conn.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));StringBuilder sb = new StringBuilder();String readline = null;while ((readline = br.readLine()) != null) {sb.append(readline);}System.out.println("result"+sb.toString());
等效于使用ByteArrayOutputStream

InputStream is = conn.getInputStream();ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len =-1 ;while ((len=is.read(buffer))!=-1) {bos.write(buffer, 0, len);}is.close();bos.close();String result = new String(bos.toByteArray());System.out.println("result"+result);

5-1,使用FileOutputStream写入文件

try {File file = new File(Environment.getExternalStorageDirectory(),DEFAULT_FILENAME);         FileOutputStream fos = new FileOutputStream(file);         String info = "I am a chinanese!";             fos.write(info.getBytes());             fos.close();System.out.println("写入成功:");} catch (Exception e) {e.printStackTrace();}

5-2,使用BufferedWriter写入文件

try {File file = new File(Environment.getExternalStorageDirectory(),DEFAULT_FILENAME);//第二个参数意义是说是否以append方式添加内容BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));String info = " hey, yoo,bitch";bw.write(info);bw.flush();System.out.println("写入成功");} catch (Exception e) {e.printStackTrace();}


读取和写入我们都实现了,貌似很简单的样子,但是我们现在想每隔30秒进行一次数据整理,然后把他们写入到我们制定的txt文件中,但是我想每次都能在上一次的结尾处开始写入,这样在电脑上通过文本打开时,就能看到每一行的数据了。

这其实要求我们每一次写入数据时,都要有换行的操作符号,比如:\n,并且IO读写能以追加的方式写入到文件里。

刚开始我很笨的想到,每次写入前,先把文件读取出来并且生成一个StringBuffer,然后再append,然后再写入.....这种方式导致每次都要2次以上的IO操作,读和写。其实系统写入时就给我们自带了append方式,还是要勤看文档啊!

BufferedWriter

使用BufferedWriter,在构造BufferedWriter时,把第二个参数设为true
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true)));
out.write(conent);

FileWriter

构造函数中的第二个参数true表示以追加形式写文件
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
writer.close();

// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
// 将写文件指针移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();



问题:我在file写入时,没一次写完后,明明都添加了换行符(bw.write("\n")),为什么在Window的文本文档中看不到换行呢?而在EditPlus或是notepad++中就能看到换行后的效果?

BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));String info = " hey, yoo,bitch";bw.write(info);bw.write("\n");bw.flush();

如上代码所示,可是在windows的文本文档中:

Android SD卡简单的文件读写操作_第1张图片

但是在诸如notepad++或EditPlus中看到却是没问题的:

Android SD卡简单的文件读写操作_第2张图片


这是为什么呢?

这是windows与linux系统的编码模式不同造成的。android系统是linux内核,与windows不同。windows是采用的是DOS编码方式,所用的换行符是DOS换行符CR/LF,也就是我们俗称的\r\n,(如果不理解可以去百度一下转义字符,一般程序员会用到这些知识),而linux系统的换行符为UNIX换行符LF,也就是\n,苹果的MAC系统用的是MAC换行符CR,也就是\r,现在我想你也差不多理解了。你在android手机里建立的文档肯定用的是UNIX换行符,也就是一个\n,但是这个文档你拿到windows里用记事本打开的话,因为windows记事本是DOS换行符\r\n,所以你少了个\r,所以没法识别成换行,只能给你识别成一个小方块了,解决办法很简单,你可以用EditPlus或者UltraEdit软件打开,UltraEdit也能转换这些编码模式,转换成DOS模式就可以了。


所以,我们只需要添加:\r\n

BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));String info = " hey, yoo,bitch";bw.write(info);bw.write("\r\n");bw.flush();


ok,先到这里,之后继续补充。

更多相关文章

  1. 【Android】图片(文件)上传的请求分析结构
  2. Android获取.Gradle文件中的值和Manifests文件中的值
  3. Android编译系统中头文件搜索路径顺序的一个问题
  4. Android中 将布局文件/View显示至手机屏幕的 整个过程分析
  5. ORMLite完全解析(四) 官方文档第四章、在Android中使用
  6. Android res/raw文件以及raw与res/assets异同
  7. Windows环境下编译Assimp库生成Android可用的.so文件

随机推荐

  1. Android(安卓)内核安全机制-selinux简介
  2. Cocos Creator 使用 Android(安卓)Studio
  3. (四)Kotlin 领域特定语言 DSL
  4. android自定义控件实例
  5. 卷二 Dalvik与Android源码分析 第二章 进
  6. android studio 2.3.1 NDK开发入门实例
  7. Python String 的replace()与List的remov
  8. 通过抢红包插件学习Accessibility Servic
  9. Android(安卓)线程消息循环机制
  10. android DHCP流程