android中的文件操作

android中的文件操作,android,Android,我是android平台的新手。我需要在android中创建一个文本文件。请让我知道如何在android中执行此任务。我已经写了一段代码,它在java中运行良好,但在android中却不行。请在这方面帮助我…我编写的示例代码是:- try { DataOutputStream dos = new DataOutputStream(new FileOutputStream("test.txt", true)); dos.writeBytes(dataLine); dos.close(); }

我是android平台的新手。我需要在android中创建一个文本文件。请让我知道如何在android中执行此任务。我已经写了一段代码,它在java中运行良好,但在android中却不行。请在这方面帮助我…我编写的示例代码是:-

try
{
DataOutputStream   dos = new DataOutputStream(new FileOutputStream("test.txt", true));
dos.writeBytes(dataLine);
dos.close();
} 
catch (FileNotFoundException ex) {}
上述代码片段在java中运行良好,但在android中运行不正常:(

谢谢, Ashish

Android开发指南:

如果你想让你创建的文件对外界可见,请使用。但正如我在评论中所说的,请确保你是“一个好公民”。即使在用户卸载你的应用程序后,这些文件仍然存在。

试试这个

final File sdcard=Environment.getExternalStorageDirectory();

button.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View arg0) {
            File path=new File(sdcard,"textfile.txt");
            try {

                BufferedWriter wr=new BufferedWriter(new FileWriter(path));
                wr.write("Your Text Here");
                wr.close();

            } catch (IOException e) {

                e.printStackTrace();
            }

        }
您还需要向清单文件添加以下权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

导入android.os.Environment;
导入android.util.Log;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileNotFoundException;
导入java.io.IOException;
导入java.io.InputStream;
导入java.math.biginger;
导入java.security.MessageDigest;
导入java.security.NoSuchAlgorithmException;
导入java.util.ArrayList;
/**
*用于常见文件操作的静态方法。
* 
*@作者卡尔·哈东(carlhartung@gmail.com)
*/
公共类文件{
私有最终静态字符串t=“FileUtils”;
//用于验证和显示有效的表单名称。
公共静态最终字符串有效\u FILENAME=“[\\\-A-Za-z0-9]*.x[ht]*ml”;
//存储路径
公共静态最终字符串FORMS_PATH=Environment.getExternalStorageDirectory()+“/odk/FORMS/”;
public static final String INSTANCES_PATH=Environment.getExternalStorageDirectory()+“/odk/INSTANCES/”;
public static final String CACHE_PATH=Environment.getExternalStorageDirectory()+“/odk/.CACHE/”;
公共静态最终字符串TMPFILE_PATH=CACHE_PATH+“tmp.jpg”;
公共静态数组列表GetValidFormSarRayList(字符串路径){
ArrayList FormPath=新的ArrayList();
文件目录=新文件(路径);
如果(!storageReady()){
返回null;
}
如果(!dir.exists()){
如果(!createFolder(路径)){
返回null;
}
}
File[]dirs=dir.listFiles();
对于(int i=0;i整数最大值){
Log.e(t,“File”+File.getName()+“太大”);
返回null;
}
//创建字节数组以保存数据
字节=新字节[(int)长度];
//读入字节
整数偏移=0;
int read=0;
试一试{
while(偏移量=0){
read=is.read(字节,偏移量,bytes.length-offset);
偏移量+=读取;
}
}捕获(IOE异常){
Log.e(t,“无法读取”+file.getName());
e、 printStackTrace();
返回null;
}
//确保已读入所有字节
if(偏移量<字节长度){
试一试{
抛出新IOException(“无法完全读取文件”+file.getName());
}捕获(IOE异常){
e、 printStackTrace();
返回null;
}
}
返回字节;
}catch(filenotfounde异常){
Log.e(t,“找不到”+file.getName());
e、 printStackTrace();
返回null;
}最后{
//关闭输入流
试一试{
is.close();
}捕获(IOE异常){
Log.e(t,“无法关闭”+file.getN的输入流
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

/**
 * Static methods used for common file operations.
 * 
 * @author Carl Hartung (carlhartung@gmail.com)
 */
public class FileUtils {
    private final static String t = "FileUtils";

    // Used to validate and display valid form names.
    public static final String VALID_FILENAME = "[ _\\-A-Za-z0-9]*.x[ht]*ml";

    // Storage paths
    public static final String FORMS_PATH = Environment.getExternalStorageDirectory() + "/odk/forms/";
    public static final String INSTANCES_PATH = Environment.getExternalStorageDirectory() + "/odk/instances/";
    public static final String CACHE_PATH = Environment.getExternalStorageDirectory() + "/odk/.cache/";
    public static final String TMPFILE_PATH = CACHE_PATH + "tmp.jpg";


    public static ArrayList<String> getValidFormsAsArrayList(String path) {
        ArrayList<String> formPaths = new ArrayList<String>();
        File dir = new File(path);

        if (!storageReady()) {
            return null;
        }
        if (!dir.exists()) {
            if (!createFolder(path)) {
                return null;
            }
        }
        File[] dirs = dir.listFiles();
        for (int i = 0; i < dirs.length; i++) {
          // skip all the directories
          if (dirs[i].isDirectory())
            continue;

            String formName = dirs[i].getName();

          formPaths.add(dirs[i].getAbsolutePath());
        }
        return formPaths;
    }

    public static ArrayList<String> getFoldersAsArrayList(String path) {
        ArrayList<String> mFolderList = new ArrayList<String>();
        File root = new File(path);

        if (!storageReady()) {
            return null;
        }
        if (!root.exists()) {
            if (!createFolder(path)) {
                return null;
            }
        }
        if (root.isDirectory()) {
            File[] children = root.listFiles();
            for (File child : children) {
                boolean directory = child.isDirectory();
                if (directory) {
                    mFolderList.add(child.getAbsolutePath());
                }
            }
        }
        return mFolderList;
    }


    public static boolean deleteFolder(String path) {
        // not recursive
        if (path != null && storageReady()) {
            File dir = new File(path);
            if (dir.exists() && dir.isDirectory()) {
                File[] files = dir.listFiles();
                for (File file : files) {
                    if (!file.delete()) {
                        Log.i(t, "Failed to delete " + file);
                    }
                }
            }
            return dir.delete();
        } else {
            return false;
        }
    }


    public static boolean createFolder(String path) {
        if (storageReady()) {
            boolean made = true;
            File dir = new File(path);
            if (!dir.exists()) {
                made = dir.mkdirs();
            }
            return made;
        } else {
            return false;
        }
    }


    public static boolean deleteFile(String path) {
        if (storageReady()) {
            File f = new File(path);
            return f.delete();
        } else {
            return false;
        }
    }


    public static byte[] getFileAsBytes(File file) {
        byte[] bytes = null;
        InputStream is = null;
        try {
            is = new FileInputStream(file);

            // Get the size of the file
            long length = file.length();
            if (length > Integer.MAX_VALUE) {
                Log.e(t, "File " + file.getName() + "is too large");
                return null;
            }

            // Create the byte array to hold the data
            bytes = new byte[(int) length];

            // Read in the bytes
            int offset = 0;
            int read = 0;
            try {
                while (offset < bytes.length && read >= 0) {
                    read = is.read(bytes, offset, bytes.length - offset);
                    offset += read;
                }
            } catch (IOException e) {
                Log.e(t, "Cannot read " + file.getName());
                e.printStackTrace();
                return null;
            }

            // Ensure all the bytes have been read in
            if (offset < bytes.length) {
                try {
                    throw new IOException("Could not completely read file " + file.getName());
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }

            return bytes;

        } catch (FileNotFoundException e) {
            Log.e(t, "Cannot find " + file.getName());
            e.printStackTrace();
            return null;

        } finally {
            // Close the input stream
            try {
                is.close();
            } catch (IOException e) {
                Log.e(t, "Cannot close input stream for " + file.getName());
                e.printStackTrace();
                return null;
            }
        }
    }


    public static boolean storageReady() {
        String cardstatus = Environment.getExternalStorageState();
        if (cardstatus.equals(Environment.MEDIA_REMOVED)
                || cardstatus.equals(Environment.MEDIA_UNMOUNTABLE)
                || cardstatus.equals(Environment.MEDIA_UNMOUNTED)
                || cardstatus.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
            return false;
        } else {
            return true;
        }
    }


    public static String getMd5Hash(File file) {
        try {
            // CTS (6/15/2010) : stream file through digest instead of handing it the byte[]
            MessageDigest md = MessageDigest.getInstance("MD5");
            int chunkSize = 256;

            byte[] chunk = new byte[chunkSize];

            // Get the size of the file
            long lLength = file.length();

            if (lLength > Integer.MAX_VALUE) {
                Log.e(t, "File " + file.getName() + "is too large");
                return null;
            }

            int length = (int) lLength;

            InputStream is = null;
            is = new FileInputStream(file);

            int l = 0;
            for (l = 0; l + chunkSize < length; l += chunkSize) {
                is.read(chunk, 0, chunkSize);
                md.update(chunk, 0, chunkSize);
            }

            int remaining = length - l;
            if (remaining > 0) {
                is.read(chunk, 0, remaining);
                md.update(chunk, 0, remaining);
            }
            byte[] messageDigest = md.digest();

            BigInteger number = new BigInteger(1, messageDigest);
            String md5 = number.toString(16);
            while (md5.length() < 32)
                md5 = "0" + md5;
            is.close();
            return md5;

        } catch (NoSuchAlgorithmException e) {
            Log.e("MD5", e.getMessage());
            return null;

        } catch (FileNotFoundException e) {
            Log.e("No Cache File", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Problem reading from file", e.getMessage());
            return null;
        } 


    }

}