Android之怎么操作文件
2014-12-22 · 知道合伙人数码行家
可以叫我表哥
知道合伙人数码行家
向TA提问 私信TA
知道合伙人数码行家
采纳数:25897
获赞数:1464984
2010年毕业于北京化工大学北方学院计算机科学与技术专业毕业,学士学位,工程电子技术行业4年从业经验。
向TA提问 私信TA
关注
展开全部
步骤如下:
一、介绍:
此主要是介绍怎么把文件写入到手机存储上、怎么从手机存储上读取文件内容以及怎么把文件写到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", "我能被读写吗?");
}
}
更多信息,请阅读此篇文章:
http://blog.csdn.net/wangkr111/article/details/7907600
一、介绍:
此主要是介绍怎么把文件写入到手机存储上、怎么从手机存储上读取文件内容以及怎么把文件写到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", "我能被读写吗?");
}
}
更多信息,请阅读此篇文章:
http://blog.csdn.net/wangkr111/article/details/7907600
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
用RE文件管理器,一直用这个的。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
文件管理器
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2014-12-22
展开全部
装一个叫文件管理器的APP,便可以了
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
5太太太太太太太太太太太太太太太太太太太太太太太太
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询