Android创建文件夹及文件并写入数据

来源:互联网 发布:xprom编程器读写教程 编辑:程序博客网 时间:2024/05/21 09:33
[java] view plain copy
 print?
  1. package elwin.fei.mobileaudio;  
  2.   
  3. import java.io.BufferedWriter;  
  4. import java.io.File;  
  5. import java.io.FileWriter;  
  6. import java.io.IOException;  
  7. import java.text.SimpleDateFormat;  
  8.   
  9. public class CreateFiles {  
  10.   
  11.     String filenameTemp = Info.audioPath + "/hhaudio" + ".txt";  
  12.       
  13.     //创建文件夹及文件  
  14.     public void CreateText() throws IOException {  
  15.         File file = new File(Info.audioPath);  
  16.         if (!file.exists()) {  
  17.             try {  
  18.                 //按照指定的路径创建文件夹  
  19.                 file.mkdirs();  
  20.             } catch (Exception e) {  
  21.                 // TODO: handle exception  
  22.             }  
  23.         }  
  24.         File dir = new File(filenameTemp);  
  25.         if (!dir.exists()) {  
  26.               try {  
  27.                   //在指定的文件夹中创建文件  
  28.                   dir.createNewFile();  
  29.             } catch (Exception e) {  
  30.             }  
  31.         }  
  32.   
  33.     }  
  34.       
  35.     //向已创建的文件中写入数据  
  36.     public void print(String str) {  
  37.         FileWriter fw = null;  
  38.         BufferedWriter bw = null;  
  39.         String datetime = "";  
  40.         try {  
  41.             SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd" + " "  
  42.                     + "hh:mm:ss");  
  43.             datetime = tempDate.format(new java.util.Date()).toString();  
  44.             fw = new FileWriter(filenameTemp, true);//  
  45.             // 创建FileWriter对象,用来写入字符流  
  46.             bw = new BufferedWriter(fw); // 将缓冲对文件的输出  
  47.             String myreadline = datetime + "[]" + str;  
  48.               
  49.             bw.write(myreadline + "\n"); // 写入文件  
  50.             bw.newLine();  
  51.             bw.flush(); // 刷新该流的缓冲  
  52.             bw.close();  
  53.             fw.close();  
  54.         } catch (IOException e) {  
  55.             // TODO Auto-generated catch block  
  56.             e.printStackTrace();  
  57.             try {  
  58.                 bw.close();  
  59.                 fw.close();  
  60.             } catch (IOException e1) {  
  61.                 // TODO Auto-generated catch block  
  62.             }  
  63.         }  
  64.     }  
  65. }
0 0