由于刚接触android开发,故此想把学到的基础知识记录一下,以备查询,故此写的比较啰嗦:
步骤如下:
一、介绍:
此主要是介绍怎么把文件写入到手机存储上、怎么从手机存储上读取文件内容以及怎么把文件写到SDCard
二、新建一个android工程——FileOperate
目录如下:
三、清单列表AndroidManifest.xml的配置为:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.files"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<!--单元测试 加这句-->
<uses-library android:name="android.test.runner" />
<activity
android:name=".FileActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- 往SDCard的创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--单元测试加这句,其中android:targetPackage为当前应用的包名
android:targetPackage 目标包是指单元测试的类的上面包和manifest的
package="com.example.main" 保持一致
这样就决定了你建立测试类的时候也必须在这个包下面
-->
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.example.files"
android:label="Test for my app"/>
</manifest>
四、FileActivity.java源码:
package com.example.files;
import java.io.FileNotFoundException;
import java.io.IOException;import com.example.service.FileService;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;public class FileActivity extends Activity {
EditText fileName ;
EditText fileContent;
Button fileSave;
OnClickListener fileSaveListener;
OnClickListener fileSaveSDListener;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fileSaveListener = new OnClickListener(){ @Override
public void onClick(View v) {
//setTitle("123");
//Toast.makeText(FileActivity.this, "123", Toast.LENGTH_LONG).show();
String fileNameStr = fileName.getText().toString();
String fileContentStr = fileContent.getText().toString();
FileService fileService = new FileService(getApplicationContext());
try {
fileService.save(fileNameStr,fileContentStr);
Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(), R.string.failure, Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
fileSaveSDListener = new OnClickListener(){ @Override
public void onClick(View v) {
//setTitle("123");
//Toast.makeText(FileActivity.this, "123", Toast.LENGTH_LONG).show();
String fileNameStr = fileName.getText().toString();
String fileContentStr = fileContent.getText().toString();
FileService fileService = new FileService(getApplicationContext());
try {
//判断SDCard是否存在并且可以读写
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
fileService.saveToSD(fileNameStr,fileContentStr);
Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(), R.string.sdcardfail, Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Button fileSave = (Button) this.findViewById(R.id.fileSave);
fileSave.setOnClickListener(fileSaveListener);
Button fileSaveSD = (Button) this.findViewById(R.id.fileSaveSD);
fileSaveSD.setOnClickListener(fileSaveSDListener);
fileName = (EditText) this.findViewById(R.id.fileName);
fileContent = (EditText) this.findViewById(R.id.fileContent);
}
}
五、FileService.java源码:
package com.example.service;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;import android.content.Context;
import android.os.Environment;public class FileService {
private Context context;public FileService(Context context) {
super();
this.context = context;
}
/**
* 写入文件到SD卡
* @throws IOException
*/
public void saveToSD(String fileNameStr, String fileContentStr) throws IOException{
//备注:Java File类能够创建文件或者文件夹,但是不能两个一起创建
File file = new File("/mnt/sdcard/myfiles");
// if(!file.exists())
// {
// file.mkdirs();
// }
// File sd=Environment.getExternalStorageDirectory();
// String path=sd.getPath()+"/myfiles";
// File file=new File(path);
// if(file.exists()){
// file.delete();
// }
if(!file.exists()){
file.mkdir();
}
File file1 = new File(file, fileNameStr); FileOutputStream fos = new FileOutputStream(file1);
fos.write(fileContentStr.getBytes());
fos.close();
}/**
* 保存文件到手机
* @param fileNameStr 文件名
* @param fileContentStr 文件内容
* @throws IOException
*/
public void save(String fileNameStr, String fileContentStr) throws IOException {
//私有操作模式:创建出来的文件只能被本应用访问,其它应用无法访问该文件,另外采用私有操作模式创建的文件,写入文件中的内容会覆盖原文件的内容
FileOutputStream fos = context.openFileOutput(fileNameStr, context.MODE_PRIVATE);
fos.write(fileContentStr.getBytes());
fos.close();
}
public void saveAppend(String fileNameStr, String fileContentStr) throws IOException {
//追加操作模式:不覆盖源文件,但是同样其它应用无法访问该文件
FileOutputStream fos = context.openFileOutput(fileNameStr, context.MODE_APPEND);
fos.write(fileContentStr.getBytes());
fos.close();
}
public void saveReadable(String fileNameStr, String fileContentStr) throws IOException {
//读取操作模式:可以被其它应用读取,但不能写入
FileOutputStream fos = context.openFileOutput(fileNameStr, context.MODE_WORLD_READABLE);
fos.write(fileContentStr.getBytes());
fos.close();
}
public void saveWriteable(String fileNameStr, String fileContentStr) throws IOException {
//写入操作模式:可以被其它应用写入,但不能读取
FileOutputStream fos = context.openFileOutput(fileNameStr, context.MODE_WORLD_WRITEABLE);
fos.write(fileContentStr.getBytes());
fos.close();
}
public void saveReadWriteable(String fileNameStr, String fileContentStr) throws IOException {
//读写操作模式:可以被其它应用读写
FileOutputStream fos = context.openFileOutput(fileNameStr,
context.MODE_WORLD_READABLE+context.MODE_WORLD_WRITEABLE);
fos.write(fileContentStr.getBytes());
fos.close();
}
/**
* 读取文件内容
* @param fileNamestr 文件名
* @return
* @throws IOException
*/
public String read(String fileNamestr) throws IOException
{
FileInputStream fis = context.openFileInput(fileNamestr);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer)) != -1){
bos.write(buffer,0,len);
}
byte[] data = bos.toByteArray();
return new String(data);
}}
六、FileServiceTest.java源码:
package com.junit.test;
import com.example.service.FileService;
import android.test.AndroidTestCase;
import android.util.Log;public class FileServiceTest extends AndroidTestCase {
/**
* 测试私有模式的读取
* @throws Exception
*/
public void testRead() throws Exception{
FileService fileService = new FileService(this.getContext());
String fileContext = fileService.read("fileSave.txt");
Log.i("FileRead", fileContext);
}
/**
* 测试追加模式的写入
* @throws Exception
*/
public void testSaveAppend() throws Exception{
FileService fileService = new FileService(this.getContext());
fileService.saveAppend("fileAppendSave.txt", "你好");
}
/**
* 测试读取模式的读取
* @throws Exception
*/
public void testSaveReadable() throws Exception{
FileService fileService = new FileService(this.getContext());
fileService.saveReadable("fileSaveReadable.txt", "wonengbeiduquma");
}
/**
* 测试写入模式的写入
* @throws Exception
*/
public void testSaveWriteable() throws Exception{
FileService fileService = new FileService(this.getContext());
fileService.saveWriteable("fileSaveWriteable.txt", "wonengbeiduquma");
}
/**
* 测试读写模式的写入
* @throws Exception
*/
public void testSaveReadWriteable() throws Exception{
FileService fileService = new FileService(this.getContext());
fileService.saveReadWriteable("fileSaveReadWriteable.txt", "我能被读写吗?");
}
}七、main.xml配置:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" > <TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/file_name" /> <EditText
android:id="@+id/fileName"
android:layout_width="match_parent"
android:layout_height="wrap_content" > <requestFocus />
</EditText> <TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/file_content" /> <EditText
android:id="@+id/fileContent"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:minLines="5"/> <Button
android:id="@+id/fileSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/file_save" /> <Button
android:id="@+id/fileSaveSD"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/file_save_sd" /></LinearLayout>
八、string.xml配置:
<?xml version="1.0" encoding="utf-8"?>
<resources> <string name="hello">Hello World, FileActivity!</string>
<string name="app_name">ExampleFileOperate</string>
<string name="file_name">文件名称</string>
<string name="file_content">文件内容</string>
<string name="file_save">文件保存到手机</string>
<string name="file_save_sd">文件保存到SD卡</string>
<string name="success">保存完成</string>
<string name="failure">保存失败</string>
<string name="sdcardfail">sdCard不存在或者写保护</string>
</resources>
九、运行为:
十、可以在另一个项目中增加测试类来测试其它应用是否可以读写这些模式下创建的文件:如FileServiceTest .java:
package com.example.junit;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;import android.test.AndroidTestCase;
import android.util.Log;public class FileServiceTest extends AndroidTestCase {
/**
* 私用,只能本应用读写,
* @throws Exception
*/
public void testAccessPrivateFile() throws Exception{
String path = "/data/data/com.example.files/files/fileSave.txt";
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer))!=-1)
{
bos.write(buffer,0,len);
}
byte[] data = bos.toByteArray();
bos.close();
fis.close();
String content = new String(data);
Log.i("FileServiceTest",content);
}
/**
* 私用 不覆盖文件,可以在文件后面追加内容
* @throws Exception
*/
public void testAccessAppendFile() throws Exception{
String path = "/data/data/com.example.files/files/fileAppendSave.txt";
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer))!=-1)
{
bos.write(buffer,0,len);
}
byte[] data = bos.toByteArray();
bos.close();
fis.close();
String content = new String(data);
Log.i("FileServiceTest",content);
}
/**
* 被其他应用程序读取,不能写入
* @throws Exception
*/
public void testAccessReadableFile() throws Exception{
String path = "/data/data/com.example.files/files/fileSaveReadable.txt";
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer))!=-1)
{
bos.write(buffer,0,len);
}
byte[] data = bos.toByteArray();
bos.close();
fis.close();
String content = new String(data);
Log.i("FileServiceTest",content);
}
/**
* 被其他应用程序写入,不能读取
* @throws Exception
*/
public void testAccessWriteableFileRead() throws Exception{
String path = "/data/data/com.example.files/files/fileSaveWriteable.txt";
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer))!=-1)
{
bos.write(buffer,0,len);
}
byte[] data = bos.toByteArray();
bos.close();
fis.close();
String content = new String(data);
Log.i("FileServiceTest",content);
}
/**
* 被其他应用程序写入,不能读取
* @throws Exception
*/
public void testAccessWriteableFileWrite() throws Exception{
String path = "/data/data/com.example.files/files/fileSaveWriteable.txt";
File file = new File(path);
FileOutputStream fos = new FileOutputStream(file,true);//第二个参数为是否要追加内容还是覆盖内容,ture为追加,false为覆盖
fos.write("nihaoya".getBytes());
fos.close();
}
/**
* 被其他应用程序可以读写
* @throws Exception
*/
public void testAccessReadWriteableFileRead() throws Exception{
String path = "/data/data/com.example.files/files/fileSaveReadWriteable.txt";
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer))!=-1)
{
bos.write(buffer,0,len);
}
byte[] data = bos.toByteArray();
bos.close();
fis.close();
String content = new String(data);
Log.i("FileServiceTest",content);
}
/**
* 被其他应用程序可以读写
* @throws Exception
*/
public void testAccessReadWriteableFileWrite() throws Exception{
String path = "/data/data/com.example.files/files/fileSaveReadWriteable.txt";
File file = new File(path);
//此写入方法append=true时为追加模式,可以不对原文件进行覆盖
FileOutputStream fos = new FileOutputStream(file,true);
fos.write("恭喜你,你能加我啦!".getBytes());
fos.close();
}
}
十一、注意事项:
1、要在sdcard创建和删除以及写入数据必须添加下面两个权限:
<!-- 往SDCard的创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2、往sdcard上写入数据是可以先判断是否有此权限:
//判断SDCard是否存在并且可以读写
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED
3、在sdcard上创建文件夹的方法(推荐后面一种方法):
File file = new File("/mnt/sdcard/myfiles");
if(!file.exists()){
file.mkdir();
} 或者
File sd=Environment.getExternalStorageDirectory();
String path=sd.getPath()+"/myfiles";
File file=new File(path);
if(!file.exists()){
file.mkdir();
}
4、多熟悉输入输出流的灵活应用