File 读写
[功能]
因为文件读写很平常 使用打算把这个功能写出辅助类的形式 以便以后方便使用 就是:FileIOHelper
[代码]
1. 定义指定的File 以及其上的 FileInputStream FileOutputStream
Context context;
File file;
FileInputStream fin;
FileOutputStream fout;
public FileIOHelper(Context c, String name,String path) throws IOException{
context = c;
file = new File(path,name);
file.createNewFile();
fin = new FileInputStream(file);
fout = new FileOutputStream(file);
}
2. 文件写
public void wrire(String s) throws IOException{
fout.write(s.getBytes());
fout.close();
}
3. 文件读
public byte[] read(int s,int l) throws IOException{
byte[] save = new byte[l];
fin.read(save, s, l);
return save;
}
4. 编码转换
public String encode(byte[] array){
return EncodingUtils.getString(array,TEXT_ENCODING);
}
5. 文件长度
public int length(){
return (int)file.length();
}
6. 如何使用FileIOHelper
public class FileIOUsage extends Activity {
public final static String NAME = "griffinshi.txt";
public final static String PATH = "data/data/com.android.FileIO";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
try {
FileIOHelper helper = new FileIOHelper(this,NAME,PATH );
String string = "Hello to Gryphone!";
helper.wrire(string);
byte[] array = helper.read(0, helper.length());
String data = helper.encode(array);
TextView tv = new TextView(this);
tv.setText(data);
setContentView(tv);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
7. 其他待解决问题
* 文件似乎只支持一次写 而不支持追加操作 不知何故 以后有时间在回头看看
8. 生成的文件:
E:\android-dev\sdk\android-sdk-windows-1.5_r2\tools>adb shell
# cd data
cd data
# cd data
cd data
# cd com.android.FileIO
cd com.android.FileIO
# ls
ls
griffinshi.txt
lib
9. 运行结果: