【Android】文件读写操作(含SDCard的读写)

本文深入探讨了Android中文件的读写操作,包括如何在默认地址保存和读取文件,详细介绍了openFileOutput和openFileInput方法的使用,以及通过字节缓冲处理文件数据的流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:【Android】文件读写操作(含SDCard的读写)

这里面的this指的是Activity对象

1. 写文件到默认地址:

public void saveAppend(String filename, String content) throws Exception  
    {
	    FileOutputStream outStream = this.openFileOutput(filename, Context.MODE_APPEND);  
	    outStream.write(content.getBytes());  
	    outStream.close();
    }


2. 读文件:

public String readFile(String filename) throws Exception  
    {  
        //获得输入流  
        FileInputStream inStream = this.openFileInput(filename);  
        //new一个缓冲区  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        //使用ByteArrayOutputStream类来处理输出流  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        while( (len = inStream.read(buffer))!= -1)  
        {  
            //写入数据  
            outStream.write(buffer, 0, len);  
        }  
        //得到文件的二进制数据  
        byte[] data = outStream.toByteArray();  
        //关闭流  
        outStream.close();  
        inStream.close();  
        return new String(data);  
    }