Android 文件读写的例子

 1 import java.io.FileInputStream; 
 2 import java.io.FileNotFoundException; 
 3 import java.io.FileOutputStream; 
 4 import java.io.IOException; 
 5 import org.apache.http.util.EncodingUtils; 
 6 
 7 public class MyLogFile { 
 8       private static FileOutputStream fout; 
 9       public MyLogFile() { 
10       } 
11 
12       public static void createFile(){
13            try {
14                 fout = new FileOutputStream("/mnt/sdcard/zyrPad.txt");
15                 // fout = openFileOutput("/mnt/sdcard/zyrPad.txt",Mode);
16           } catch (FileNotFoundException e) {
17                 e.printStackTrace(); 
18           } 
19      } 
20 
21      //写在/mnt/sdcard/目录下面的文件 
22      public static void writeFileSdcard(String message){ 
23            try{ 
24                  //FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);
25                 message= message+"\n";
26                 byte [] bytes = message.getBytes(); 
27                 fout.write(bytes); 
28            } catch(Exception e){
29                 e.printStackTrace();
30            }
31       }
32 
33       //读在/mnt/sdcard/目录下面的文件 
34       public String readFileSdcard(String fileName){
35             String res="";
36             try{ 
37                   FileInputStream fin = new FileInputStream(fileName);
38                   int length = fin.available(); 
39                   byte [] buffer = new byte[length]; 
40                   fin.read(buffer); 
41                   res = EncodingUtils.getString(buffer, "UTF-8"); 
42                   fin.close();
43             } catch(Exception e){ 
44                   e.printStackTrace();
45             }
46             return res; 
47       } 
48 
49       /** * 关闭文件流 */ 
50       public static void closeFile(){
51             try {
52                  fout.close(); 
53             } catch (IOException e) {
54                  e.printStackTrace(); 
55             }
56       } 
57 } 

调用的时候很简单:
MyLogFile.createFile();//创建文件
MyLogFile.writeFileSdcard("------------写文字到文件中----------------");

使用完后,记得关闭:
MyLogFile.closeFile()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值