Android读写文件的代码

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

写入数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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();
                  }
        }
   }

读取数据:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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;
     }

用法:
1
2
WriteSettings(this,"setting0, setting1, setting2");
String data[] = ReadSettings(this).split(",");