最近在学习安卓相关的编程,对于一门新技术的学习,我想应该跟其他语言一样吧,如C++和C#,也是文件,网络,多线程以及数据库之类的学习了。所以决定先从文件下手,现在将文件的一点学习列在下面:

1.Java中文件的操作

Java中文件的操作分为两种类型:字节型(Stream)和字符型(Reader),但是字符型在处理非文本类型的数据时会有问题。

好了上一段代码:

/**
* 文件的复制
* @param srcPath 源文件路径
* @param destPath 目标文件路径
* @throws Exception 抛出的异常
*/
public static void copy(String srcPath, String destPath) throws Exception{
File src = new File(srcPath);
File dest = new File(destPath); InputStream input = new BufferedInputStream(new FileInputStream(src));
OutputStream output = new BufferedOutputStream(new FileOutputStream(dest)); int len = 0;
byte[] buffer = new byte[1024];
while(-1 != (len = input.read(buffer))){
output.write(buffer,0,len);
} output.close();
input.close();
}

这段代码的主要功能是复制源文件到目标文件,需要特别注意的是,目标文件必须指定文件名,如果是路径的话,会出错。

File src = new File(srcPath);
File dest = new File(destPath);

这两句话的意思是与文件建立联系,以便让后面的流进行操作,当然也可以直接在流中指定文件的路径。

InputStream input = new BufferedInputStream(new FileInputStream(src));

这边就是声明输出流了,因为是将外部文件导入到程序中,所以需要使用FileInputStream,这也可以理解。那么BufferedInputStream是有什么作用呢?使用BufferedInputStream对FileInputStream进行装饰,使普通的文件输入流具备了内存缓存的功能,通过内存缓冲减少磁盘IO次数,看到别人博客上的一句话,说的清晰明了就拿过来用了。对于BufferedOutputStream,其作用是类似的。
另外,在input.read()处理到文件末尾的时候就会返回-1,以此来判断文件是否读取结束。对于output.close()内部会调用flush方法将缓存的数据写进文件,最后记得关闭流。

在这里关于异常的是直接抛出的,因为这个方法是逻辑层,所以异常处理交给业务层。

2.Android文件的操作

public class FileService {
private FileService() { } public static void write(String fileName, String content) throws Exception {
File file = new File(fileName);// 建立连接
OutputStream output = new BufferedOutputStream(new FileOutputStream(
file));
output.write(content.getBytes());
output.close();
}
}

既然在Java中可以使用该代码,那么在android中应这段代码就应该是可用的。但是在执行的时候发生了错误:

打开文件错误:只读文件系统 open failed:EROFS(read only file system)

这是什么原因呢?后来在stack overflow上找到了下面一段话:

You will not have access to the file-system root, which is what you're attempting to access. For your purposes, you can write to internal files new File("test.png"), which places the file in the application-internal storage -- better yet, access it explicitly using getFilesDir().

大致意思是,app没有系统root目录的权限,也就是说,我直接创建file的时候,是在系统的根目录上创建的,然而所写的App没有相关的权限。但是可以写在手机的内部存储器上,通过getFilesDir()来获取内部的目录。更新代码如下:

package org.tonny.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.OutputStream; import android.content.Context; public final class FileService {
private Context context; public FileService(Context context) {
this.context = context;
} public void write(String fileName, String content) throws Exception {
File file = new File(context.getFilesDir() + File.separator + fileName);// 建立连接
OutputStream output = new BufferedOutputStream(new FileOutputStream(
file));
output.write(content.getBytes());
output.close();
}
}

这样修改之后,果然可以创建文件了。那么android是否提供了另外的方法来进行相关的操作了,经过一番查阅,发现还是有的,代码如下:

package org.tonny.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.OutputStream; import android.content.Context; public final class FileService {
private Context context; public FileService(Context context) {
this.context = context;
} public void write(String fileName, String content) throws Exception {
File file = new File(context.getFilesDir() + File.separator + fileName);// 建立连接
OutputStream output = new BufferedOutputStream(new FileOutputStream(
file));
output.write(content.getBytes());
output.flush();
output.close();
} public void writeFile(String fileName, String content) throws Exception{
OutputStream output = new BufferedOutputStream(context.openFileOutput(fileName, Context.MODE_PRIVATE));
output.write(content.getBytes());
output.flush();
output.close();
} }

同样是可以在app相应的目录下创建文件。

那么可以在文件的内部存储器存放文件,如何在SD卡上存放文件呢,网上的例子还是比较多的,代码如下:

public void writeSDFile(String fileName, String content) throws Exception {
boolean sdCardExist = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
if (!sdCardExist) {
// SD卡不存在,则退出
return;
}
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + File.separator + fileName);
OutputStream output = new BufferedOutputStream(new FileOutputStream(
file));
output.write(content.getBytes());
output.flush();
output.close();
}

这里需要先判断一下SD卡是否存在,存在才能进一步操作,同时需要在清单文件中配置

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

代码是写好了,简单的重构一下:

package org.tonny.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream; import android.content.Context;
import android.os.Environment; public final class FileService {
private Context context; public FileService(Context context) {
this.context = context;
} public void write(String fileName, String content) throws Exception {
File file = new File(context.getFilesDir() + File.separator + fileName);// 建立连接
oper(file, content);
} public void writeFile(String fileName, String content) throws Exception {
OutputStream output = new BufferedOutputStream(context.openFileOutput(
fileName, Context.MODE_PRIVATE));
output.write(content.getBytes());
output.flush();
output.close();
} public void writeSDFile(String fileName, String content) throws Exception {
boolean sdCardExist = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
if (!sdCardExist) {
// SD卡不存在,则退出
return;
}
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + File.separator + fileName);
oper(file, content);
} /**
* 文件写操作
*
* @param file
* @param content
* @throws Exception
*/
private void oper(File file, String content) throws Exception {
OutputStream output = new BufferedOutputStream(new FileOutputStream(
file));
output.write(content.getBytes());
output.flush();
output.close();
}
}

由于学习还在一个较浅的层面,所以就写了这几个简单的例子。还有很多内容有待丰富,如文件的属性获取,复制以及读取等操作都没有写。另外没有从整体上介绍Android IO操作类的结构,所以文章还是有些混乱的。哎,第一次写,时间花了不少,休息啦。

Android学习一:文件操作的更多相关文章

  1. Android数据存储-文件操作

    一.预备知识 1.Android中的MVC设计模式 MVC (Model-View-Controller):M是指逻辑模型,V是指视图模型,C则是控制器.一个逻辑模型可以对于多种视图模型,比如一批统计 ...

  2. Android的file文件操作详解

    Android的file文件操作详解 android的文件操作要有权限: 判断SD卡是否插入 Environment.getExternalStorageState().equals( android ...

  3. HTML5学习之文件操作(九)

    之前我们操作本地文件都是使用flash.silverlight或者第三方的activeX插件等技术,由于使用了这些技术后就很进行跨平台的处理,另外就是让我们的web应用依赖了第三方的插件,而不是很独立 ...

  4. python学习笔记:文件操作和集合(转)

    转自:http://www.nnzhp.cn/article/16/ 这篇博客来说一下python对文件的操作. 对文件的操作分三步: 1.打开文件获取文件的句柄,句柄就理解为这个文件 2.通过文件句 ...

  5. android中的文件操作详解以及内部存储和外部存储(转载)

    原文链接:http://m.blog.csdn.net/article/details?id=17725989 摘要 其实安卓文件的操作和java在pc环境下的操作并无二致,之所以需要单独讲解是因为安 ...

  6. 【转】 android中的文件操作详解以及内部存储和外部存储

    摘要 其实安卓文件的操作和Java在pc环境下的操作并无二致,之所以需要单独讲解是因为安卓系统提供了不同于pc的访问文件系统根路径的api,同时对一个应用的私有文件做了统一的管理.根据我的经验,初学者 ...

  7. python学习总结---文件操作

    # 文件操作 ### 目录管理(os) - 示例 ```python # 执行系统命令 # 清屏 # os.system('cls') # 调出计算器 # os.system('calc') # 查看 ...

  8. erlang学习笔记(文件操作)

    参考这里和这里了解到的文件操作的模块有很多:kernel下有:file,stdlib下有:filelib,filename,file_sorter.(具体查看官方文档)

  9. Smart210学习记录-------文件操作

    一.linux文件操作(只能在linux系统上用) 创建:int creat(const char* filename, mode_t mode) filename 表示要创建的文件名,mode表示对 ...

  10. NodeJS学习之文件操作

    NodeJS -- 文件操作 Buffer(数据块) JS语言自身只有字符串数据类型,没有二进制数据类型,因此NodeJS提供了一个与String对等的全局构造函数Buffer来提供对二进制数据的操作 ...

随机推荐

  1. STM32学习笔记(六) SysTick系统时钟滴答实验(stm32中断入门)

    系统时钟滴答实验很不难,我就在面简单说下,但其中涉及到了STM32最复杂也是以后用途最广的外设-NVIC,如果说RCC是实时性所必须考虑的部分,那么NVIC就是stm32功能性实现的基础,NVIC的难 ...

  2. myeclipse/eclipse没有Project Facets的解决方法

    http://www.cnblogs.com/jerome-rong/archive/2012/12/18/2822783.html 经常在eclipse中导入web项目时,出现转不了项目类型的问题, ...

  3. js高级程序设计(六)面向对象

    ECMA-262 把对象定义为:“无序属性的集合,其属性可以包含基本值.对象或者函数.”严格来讲,这就相当于说对象是一组没有特定顺序的值.对象的每个属性或方法都有一个名字,而每个名字都映射到一个值.正 ...

  4. Unity NGUI 2D场景添加按钮

    比如说先添加一个sprite 在sprite加上NGUI的 UI Button 然后重点来了  加上Box Collider 2D(重点:2D 千万不要加 Box Collider) 将Box Col ...

  5. CentOS7 安装RabbitMQ

    第一.下载erlang和rabbitmq-server的rpm: http://www.rabbitmq.com/releases/erlang/erlang-19.0.4-1.el7.centos. ...

  6. win7任务栏只显示日期不显示年月日

    某一天突然发现笔记本任务栏上的时间显示只剩下了时间,没有了年月日 于是百度 搜到的结果大多是如何设置显示的格式  yyyy-MM-dd 继续搜 终于搜到了正确答案 结果令我瞠目结舌  着实无奈 是因为 ...

  7. Intellij快捷键

  8. 美女程序员是如何将QQ转换成题目中那串数字的--读博文《找女神要QQ号码》

    我只能说好好的端午节你们不约么?,还在这里写代码?我也是够无聊的,下班了不走也在这跟风写着玩!<找女生要QQ号码原文>原文链接http://www.cnblogs.com/iforever ...

  9. centos55_oracle11gr2_install

    第一个阶段:安装centos55 a:安装centos5.5   用图形界面安装  硬盘 16G 注意:用图形界面安装.. 第二个阶段:配置1:检查内存情况# grep MemTotal /proc/ ...

  10. 使用Jsoup 抓取页面的数据

    需要使用的是jsoup-1.7.3.jar包   如果需要看文档我下载请借一步到官网:http://jsoup.org/ 这里贴一下我用到的 Java工程的测试代码 package com.javen ...