androi文件读写操作
废话少说,直接上代码,看不懂的地方自己去网上查,以下代码都在我本地运行正常:
新建一个FileRW的android的项目:
新建一个com.sharandroi.file包
新建一个FileService.java的具体操作类:
package com.sharandroi.file;
import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import android.content.Context;
public class FileService { private Context context;
public FileService(Context context) { this.context = context; }
public void save(String content) throws Exception { FileOutputStream outStream = context.openFileOutput("sharpandroid.txt", Context.MODE_WORLD_WRITEABLE); outStream.write(content.getBytes());// 写数据 outStream.close();// 关闭输出流 }
public String read() throws Throwable{ FileInputStream instream = context.openFileInput("sharpandroid.txt"); byte data = readFile(instream); return new String(data); }
public byte readFile(InputStream inStream) throws Throwable{ int len = 0; byte buffer = new byte; ByteArrayOutputStream outStream = new ByteArrayOutputStream(); while((len = inStream.read(buffer))!=-1){ outStream.write(buffer,0,len); } outStream.close(); return outStream.toByteArray(); } }
新建一个单元测试类:FileServiceTest.java
package com.sharandroi.file;
import java.io.InputStream; import java.io.OutputStream; import android.content.Context; import android.test.AndroidTestCase; import android.util.Log;
public class FileServiceTest extends AndroidTestCase { public void testSave() throws Throwable{ FileService fileService = new FileService(getContext()); fileService.save("qqqqqqqqqqqqqqqqqqqqqqqqqq"); Log.i("aaa", fileService.read()); } }
AndroidManifest.xml配置添加权限:
上面的代码把需要用的包都导进来在我本地能跑起来
File Exploreer的下面看到data/data/com.sharandroi.file/下面有个sharpandroid.txt文件倒出来就可以看到内容了