Android读写文件的代码

2015-01-15 0 1,030
Android读写文件的代码

写入数据

  public void WriteSettings(Context context, String data){ 
      FileOutputStream fOut = null; 
      OutputStreamWriter osw = null; 

      try{ 
       fOut = openFileOutput("settings.dat",MODE_PRIVATE);       
          osw = new OutputStreamWriter(fOut); 
          osw.write(data); 
          osw.flush(); 
          Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show(); 
          } 
          catch (Exception e) {       
          e.printStackTrace(); 
          Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show(); 
          } 
          finally { 
             try { 
                    osw.close(); 
                    fOut.close(); 
                    } catch (IOException e) { 
                    e.printStackTrace(); 
                    } 
          } 
     }

读取数据:

public String ReadSettings(Context context){ 
      FileInputStream fIn = null; 
      InputStreamReader isr = null; 

      char[] inputBuffer = new char[255]; 
      String data = null; 

      try{ 
       fIn = openFileInput("settings.dat");       
          isr = new InputStreamReader(fIn); 
          isr.read(inputBuffer); 
          data = new String(inputBuffer); 
          Toast.makeText(context, "Settings read",Toast.LENGTH_SHORT).show(); 
          } 
          catch (Exception e) {       
          e.printStackTrace(); 
          Toast.makeText(context, "Settings not read",Toast.LENGTH_SHORT).show(); 
          } 
          finally { 
             try { 
                    isr.close(); 
                    fIn.close(); 
                    } catch (IOException e) { 
                    e.printStackTrace(); 
                    } 
          } 
          return data; 
     } 

用法:

WriteSettings(this,"setting0, setting1, setting2");
String data[] = ReadSettings(this).split(",");

遇见资源网 java Android读写文件的代码 http://www.ox520.com/8387.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务