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


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

      

  接着在使用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的文本文档中:


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



这是为什么呢?

这是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. NPM 和webpack 的基础使用
  2. 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
  3. 【阿里云镜像】切换阿里巴巴开源镜像站镜像——Debian镜像
  4. Android应用程序apk内xml文件编码解析
  5. Android开发实践:Android.mk模板
  6. Android实现关机与重启的几种方式(推荐)
  7. Android菜单详解
  8. Android如何检测网络的类型为3G、2G、wap、wifi
  9. Android数据保存之文件保存

随机推荐

  1. SIM卡基本小知识
  2. Android(安卓)HAL实例学习-Jollen的mokoi
  3. Android 自定义控件之ViewPager Indicato
  4. Android(安卓)JNI简介
  5. Android ExecutorService线程池
  6. android点击手机返回键触发事件
  7. android之下载文件
  8. Activity生命周期,状态保存恢复(经典)
  9. Android 实现九宫格、点击图片放大全屏浏
  10. android USB绑定功能实现(framework)