Android - 文件读写操作 总结

Android - 文件读写操作 总结
http://blog.csdn.net/ztp800201/article/details/7322110

 

android的文件操作。(未整理完成)
http://blog.csdn.net/fenghome/article/details/5668598

 

Android 异常处理:java.lang.IllegalArgumentException(...contains a path separator)
http://blog.csdn.net/alex_zhuang/article/details/7340901

 

//Test in main()

String fileName = "/data/data/com.example.fileoperation/files/test.txt";

String str = "This is for test string";

readFileData(fileName);
writeFileData(fileName, str);


// read file input stream
File file = new File("/data/data/com.example.fileoperation/test.txt");
FileInputStream fin = new FileInputStream(file);
// code above is equivalent to below:

/* Android Activity独有的方法,读写文件进程序自己目录下的files文件夹,若文件不存在,则自动创建之;
如我的程序在:/data/data/com.example.fileoperation, 则test.txt文件在:
/data/data/com.example.fileoperation/files/test.txt
*/ 
FileInputStream fin = openFileInput(fileName);  
// write file output stream
File file = new File("/data/data/com.example.fileoperation/test.txt");
FileOutputStream fout = new FileOutputStream(file);
// code above is equivalent to below:

FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);

 

读写SD卡:

String fileName = "/sdcard/test.txt";
//也可以用String fileName = "mnt/sdcard/test.txt";

// write SDCard
    private void writeFileSdcardFile(String fileName, String writeStr) throws IOException {
        try {
            
            FileOutputStream fout = new FileOutputStream(fileName);
            byte[] bytes = writeStr.getBytes();
            
            fout.write(bytes);
            fout.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    //    read SDCard
    private String readFileSdcardFile(String fileName) throws IOException {
        String res = "";
        try {
            
            FileInputStream fin = new FileInputStream(fileName);
            int length = fin.available();
            
            byte[] buffer = new byte[length];
            fin.read(buffer);
            
            res = EncodingUtils.getString(buffer, "UTF-8");
            
            fin.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

 

 

你可能感兴趣的:(android)