Android 檔案讀寫的例子

來源:互聯網
上載者:User

標籤:

 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()

Android 檔案讀寫的例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.