Android 高效的实现文本的追加

来源:互联网 发布:比特币编程 编辑:程序博客网 时间:2024/06/06 05:27
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.Environment;

public class SaveLogToDir
{
    private static RandomAccessFile randomFile = null;
    private static File log = null;
    public static synchronized void saveLog(String className, String log)
    {
        String saveDirFile = getDownFileStorePath("/ptt_log");
        if(!"".equals(saveDirFile))
        {
            String filetextname = getCurrentTime();
            writeSDFile_RandomAccessFile(saveDirFile,log,filetextname + ".txt",className);
        }
    }
    
    
    private static String getDownFileStorePath(String paperfile)  //传递一个
     {
         File sdDir = null;
         boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    
         if (hasSDCard) {
         sdDir = Environment.getExternalStorageDirectory();
         }
    
         File destDir = new File(sdDir.toString() + paperfile);//"/cardImages"
         if (!destDir.exists()) {
         destDir.mkdirs();
         }
         return destDir.toString();
     }
    
    /**
     * 在SD卡上创建文件
     *
     * @throws IOException
     */
    private static File createSDFile(String sdpath,String fileName) throws IOException
    {
     File file = new File(sdpath + "//" + fileName);
     if (!file.exists()) {
     file.createNewFile();
     }
     return file;
     }
    
    
    private static String getCurrentTime()
    {
         SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy年MM月dd日");
         Date date = new Date(System.currentTimeMillis());
         return dateFormat1.format(date);
    }
    
    private static String getCurrentLongTime()
    {
         SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
         Date date = new Date(System.currentTimeMillis());
         return dateFormat2.format(date);
    }
    
     /**
         * 写入内容到SD卡中的txt文本中
         * str为内容
         */
    private static void writeSDFile_RandomAccessFile(String sdfile,String str,String fileName,String className)
    {
       try
         {
             log = createSDFile(sdfile,fileName);         
             randomFile = new RandomAccessFile(sdfile+"/"+fileName, "rw");  
             // 文件长度,字节数  
             long fileLength = randomFile.length();  
             //将写文件指针移到文件尾。  
             randomFile.seek(fileLength);  
             randomFile.writeUTF(str.toString());
             randomFile.close();

         } catch (Exception e) {
       }
    }    

    
}

0 0