android 处理txt文件类FileUtils,利用java反射机制访问非sdk类和函数

来源:互联网 发布:flac mac 播放 编辑:程序博客网 时间:2024/04/29 23:38

Android系统内部提供了一个不错的txt文本读写类,但目前并没有公开提供给标准的SDK,FileUtils类的源代码如下,可以很好的操作Linux下的文本文件。
public class FileUtils
{
    public static final int S_IRWXU = 00700;
    public static final int S_IRUSR = 00400;
    public static final int S_IWUSR = 00200;
    public static final int S_IXUSR = 00100;

    public static final int S_IRWXG = 00070;
    public static final int S_IRGRP = 00040;
    public static final int S_IWGRP = 00020;
    public static final int S_IXGRP = 00010;

    public static final int S_IRWXO = 00007;
    public static final int S_IROTH = 00004;
    public static final int S_IWOTH = 00002;
    public static final int S_IXOTH = 00001;
   
     public static final class FileStatus {
        public int dev;
        public int ino;
        public int mode;
        public int nlink;
        public int uid;
        public int gid;
        public int rdev;
        public long size;
        public int blksize;
        public long blocks;
        public long atime;
        public long mtime;
        public long ctime;
    }
   

    public static native boolean getFileStatus(String path, FileStatus status);

    private static final Pattern SAFE_FILENAME_PATTERN = Pattern.compile("[//w%+,./=_-]+");


    public static boolean copyFile(File srcFile, File destFile) {
        boolean result = false;
        try {
            InputStream in = new FileInputStream(srcFile);
            try {
                result = copyToFile(in, destFile);
            } finally  {
                in.close();
            }
        } catch (IOException e) {
            result = false;
        }
        return result;
    }
   

    public static boolean copyToFile(InputStream inputStream, File destFile) {
        try {
            if (destFile.exists()) {
                destFile.delete();
            }
            OutputStream out = new FileOutputStream(destFile);
            try {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) >= 0) {
                    out.write(buffer, 0, bytesRead);
                }
            } finally {
                out.close();
            }
            return true;
        } catch (IOException e) {
            return false;
        }
    }

     public static boolean isFilenameSafe(File file) {
        return SAFE_FILENAME_PATTERN.matcher(file.getPath()).matches();
    }


    public static String readTextFile(File file, int max, String ellipsis) throws IOException {
        InputStream input = new FileInputStream(file);
        try {
            long size = file.length();
            if (max > 0 || (size > 0 && max == 0)) { 

                if (size > 0 && (max == 0 || size < max)) max = (int) size;
                byte[] data = new byte[max + 1];
                int length = input.read(data);
                if (length <= 0) return "";
                if (length <= max) return new String(data, 0, length);
                if (ellipsis == null) return new String(data, 0, max);
                return new String(data, 0, max) + ellipsis;
            } else if (max < 0) {  // "tail" mode: keep the last N
                int len;
                boolean rolled = false;
                byte[] last = null, data = null;
                do {
                    if (last != null) rolled = true;
                    byte[] tmp = last; last = data; data = tmp;
                    if (data == null) data = new byte[-max];
                    len = input.read(data);
                } while (len == data.length);

                if (last == null && len <= 0) return "";
                if (last == null) return new String(data, 0, len);
                if (len > 0) {
                    rolled = true;
                    System.arraycopy(last, len, last, 0, last.length - len);
                    System.arraycopy(data, 0, last, last.length - len, len);
                }
                if (ellipsis == null || !rolled) return new String(last);
                return ellipsis + new String(last);
            } else { 
                ByteArrayOutputStream contents = new ByteArrayOutputStream();
                int len;
                byte[] data = new byte[1024];
                do {
                    len = input.read(data);
                    if (len > 0) contents.write(data, 0, len);
                } while (len == data.length);
                return contents.toString();
            }
        } finally {
            input.close();
        }
    }
}

 

网上的搜索到的信息

 

android系统中,有很多类和方法是@hide属性的,这意味着这些类和方法是不会出现在androidsdk中的。但是有的时候我们的程序却需要调用这些个类和方法来完成一些工作。怎么办呢?一个办法是把这些个类和方法从android源代码中拷贝出来,放到我们的程序中一起编译使用。不过有可能会遇到一个比较极端的情况,那就是你花费了很久,终于把自己的程序编译成功了,却发现你几乎把整个android
framework的源代码都拷贝出来了。有些时候这样显然是得不偿失的。你花费了大量的时间,却收效甚微。那我们现在来看一下第二种方法,利用java的反射机制。关于java的反射机制大家可以参考java的文档或者网络上一些关于这个方面的文章。这里,我只介绍如何在android里使用。下面看一个例子(将黄色的代码复制一下就可以测试了,方法都是上面的)。
try {
        Class<?> hideClass = Class.forName("android.os.FileUtils");
        //Method hideSubprocess = hidecClass.getMethod("createSubprocess",
        //        String.class, String.class, String.class, int[].class);
        Method[] hideMethod = hideClass.getMethods();
        int i = 0;
        for (;i < hideMethod.length;i++)
        {
            Log.i(LOG_TAG,hideMethod[i].getName());
        }

        Method copyFile = hideClass.getMethod("copyFile", File.class,File.class);
        File tmpPackageFile  = getFileStreamPath(TMP_FILE_NAME);
        if (tmpPackageFile == null) {
                         Log.w(LOG_TAG, "Failed to create temp file");
                         return ;
                     }
                     if (tmpPackageFile.exists()) {
                         tmpPackageFile.delete();
                     }
        //this.openFileOutput("", mode);
        try {
            copyFile.invoke(hideClass.newInstance(), new File("/sdcard/MainActivity.apk"),tmpPackageFile);
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }catch (ClassNotFoundException e) {
            //throw new RuntimeException(e.getMessage());
            e.printStackTrace();
        } catch (SecurityException e) {
            //throw new RuntimeException(e.getMessage());
               e.printStackTrace();
        } catch (IllegalArgumentException e) {
            //throw new RuntimeException(e.getMessage());
               e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
其实使用基本上和一般的java reflection没有什么很大的区别。

 

还有一种整理好的TextFileUtils

package com.my.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 *文本文件常用的创建、写入、读取、删除
 *
 *@2010-8-19
 *@下午03:36:12
 */

public class TextFileUtils {

    /**
     *  创建Text文件
     * @param path
     */
    public static void createText(final String path) {
        File  filename ;
        try {
            filename = new File(path);
            if (!filename.exists()) {
                filename.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }// end method createText()

    /**
     * 删除Text文件
     * @param path
     */
    public void deleteText(String path) {
        try {
            RandomAccessFile file = new RandomAccessFile(path, "rw");
            file.setLength(0);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 读取text内容
     * @param path
     * @return
     */
    public static String readText(String path) {
        FileReader fileread;
        File filename = new File(path);
        String line = null;
        try {
            fileread = new FileReader(filename);
            BufferedReader bfr = new BufferedReader(fileread);
            try {
                line = bfr.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return line;
    }// end method readText()

    /**
     * 向Text文件中写入内容
     * @param body
     * @param path
     */
    public static void writeText(String content, String path) {
        // 先读取原有文件内容,然后进行写入操作
        RandomAccessFile mm = null;
        File filename = new File(path);
        try {
            mm = new RandomAccessFile(filename, "rw");
            mm.writeBytes(content);
        } catch (IOException e1) {
            // TODO 自动生成 catch 块
            e1.printStackTrace();
        } finally {
            if (mm != null) {
                try {
                    mm.close();
                } catch (IOException e2) {
                    // TODO 自动生成 catch 块
                    e2.printStackTrace();
                }
            }
        }
    }// end method writeText()

}

 

 

原创粉丝点击