当前位置: 代码迷 >> Android >> android java 资料的读写(转)
  详细解决方案

android java 资料的读写(转)

热度:19   发布时间:2016-05-01 20:29:03.0
android java 文件的读写(转)

  1. package?xiaohang.zhimeng;??
  2. ??
  3. import?java.io.FileInputStream;??
  4. import?java.io.FileOutputStream;??
  5. import?org.apache.http.util.EncodingUtils;??
  6. import?android.app.Activity;??
  7. import?android.graphics.Color;??
  8. import?android.os.Bundle;??
  9. import?android.widget.TextView;??
  10. ??
  11. public?class?Activity01?extends?Activity{??
  12. ????//常量,为编码格式??
  13. ????public?static?final?String?ENCODING?=?"UTF-8";??
  14. ????//定义文件的名称??
  15. ????String?fileName?=?"test.txt";??
  16. ????//写入和读出的数据信息??
  17. ????String?message?=?"欢迎大家来我们群里讨论问题";??
  18. ????TextView?textView;??
  19. ?????@Override??
  20. ????protected?void?onCreate(Bundle?savedInstanceState)?{??
  21. ????????super.onCreate(savedInstanceState);??
  22. ????????setContentView(R.layout.main);??
  23. ????????writeFileData(fileName,?message);??
  24. ????????String?result?=?readFileData(fileName);??
  25. ????????textView?=?(TextView)findViewById(R.id.tv);??
  26. ????????textView.setTextColor(Color.GREEN);??
  27. ????????textView.setTextSize(20.0f);??
  28. ????????textView.setText(result);??
  29. ??????????
  30. ????}??
  31. ?????//向指定的文件中写入指定的数据??
  32. ?????public?void?writeFileData(String?filename,?String?message){??
  33. ?????????try?{??
  34. ????????????FileOutputStream?fout?=?openFileOutput(filename,?MODE_PRIVATE);//获得FileOutputStream??
  35. ????????????//将要写入的字符串转换为byte数组??
  36. ????????????byte[]??bytes?=?message.getBytes();??
  37. ????????????fout.write(bytes);//将byte数组写入文件??
  38. ????????????fout.close();//关闭文件输出流??
  39. ????????}?catch?(Exception?e)?{??
  40. ????????????e.printStackTrace();??
  41. ????????}??
  42. ?????}??
  43. ???????
  44. ?????//打开指定文件,读取其数据,返回字符串对象??
  45. ?????public?String?readFileData(String?fileName){??
  46. ?????????String?result="";??
  47. ?????????try?{??
  48. ????????????FileInputStream?fin?=?openFileInput(fileName);??
  49. ????????????//获取文件长度??
  50. ????????????int?lenght?=?fin.available();??
  51. ????????????byte[]?buffer?=?new?byte[lenght];??
  52. ????????????fin.read(buffer);??
  53. ????????????//将byte数组转换成指定格式的字符串??
  54. ????????????result?=?EncodingUtils.getString(buffer,?ENCODING);??
  55. ????????}?catch?(Exception?e)?{??
  56. ????????????e.printStackTrace();??
  57. ????????}??
  58. ????????return?result;??
  59. ?????}??
  60. } ?
  相关解决方案