Android写入和读取文件

 /**
     * 读取文件
     */
    public void readFile(View view) {// 很多初学者都会犯的错误
        try {
            FileInputStream fis = openFileInput("file.txt");
            byte[] bytes = new byte[20];
            fis.read(bytes);
            System.out.println("content:" + new String(bytes));
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入文件
     */
    public void writeFile(View view) {
        // 创建一个文件,程序自身可以读写
        try {
            FileOutputStream fos = openFileOutput("file.txt", Context.MODE_PRIVATE);
            fos.write("data".getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

猜你喜欢

转载自blog.csdn.net/danwuxie/article/details/85135184