Android文件简单读写操作

MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.commons.io.FileUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
public class MainActivity extends AppCompatActivity {
    private Button bt1, bt2, bt3, bt4, bt5, bt6, bt7;
    private EditText save,write;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt1= (Button) findViewById(R.id.save);
        bt2= (Button) findViewById(R.id.write);
        bt3 = (Button) findViewById(R.id.copy);
        bt4 = (Button) findViewById(R.id.copy1);
        bt5 = (Button) findViewById(R.id.copy2);
        bt6 = (Button) findViewById(R.id.copy3);
        bt7 = (Button) findViewById(R.id.copy4);
        save= (EditText) findViewById(R.id.text1);
        write= (EditText) findViewById(R.id.text2);
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//              File sdcard= Environment.getExternalStorageDirectory();
//              File file=new File(sdcard,"1111.text");
                
                File directory = new File("/mnt/sdcard/Test/");
                File file = new File("/mnt/sdcard/Test/test.txt");
                if(!directory.exists()){
                    directory.mkdir();//没有目录先创建目录  
//                    Toast.makeText(getApplicationContext(), "创建目录成功", Toast.LENGTH_SHORT).show();
                }
                try {
                    if(!file.exists()){
                        file.createNewFile();
                    }
                    FileOutputStream fos=new FileOutputStream(file);
                    OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");//读写文件要保持统一编码方式,否则读取为乱码
                    osw.write(save.getText().toString());
                    osw.flush();
                    osw.close();
                    fos.close();
                    Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        //字节流读写数据
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    File directory = new File("/mnt/sdcard/Test/");
                    File file = new File("/mnt/sdcard/Test/test.txt");
                    if(!directory.exists()){
                        directory.mkdir();
                    }
//                  File sdcard= Environment.getExternalStorageDirectory();
//                  File file=new File(sdcard,"1111.text");
                    FileInputStream fis=new FileInputStream(file);
                    InputStreamReader isr = new InputStreamReader(fis, "utf-8");//读写文件要保持统一编码方式,否则读取为乱码
                    char input[] = new char[fis.available()];//获取fis长度
                    isr.read(input);
                    isr.close();
                    fis.close();
                    write.setText(new String(input));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        //带缓冲的字节流读写数据
        bt3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    File ifile = new File("/mnt/sdcard/Download/3.gif");//目标文件
                    File wfile = new File("/mnt/sdcard/Test/3.gif");//复制文件
                    FileInputStream fis = new FileInputStream(ifile);
                    FileOutputStream fos = new FileOutputStream(wfile);
                    //使用缓存,复制文件效率更高
//                  BufferedInputStream bis=new BufferedInputStream(fis);
//                  BufferedOutputStream bos=new BufferedOutputStream(fos);
                    //添加上缓存大小,应该比byte数组in[]大一些,但也不需要过大,具体适合大小,根据测试消耗时长定
                    BufferedInputStream bis = new BufferedInputStream(fis, 1000);
                    BufferedOutputStream bos = new BufferedOutputStream(fos, 1000);
                    long before = System.currentTimeMillis();
                    //大型文件数组大小可以大一些,小文件对应数组小一些
                    byte in[] = new byte[100];
                    //通过循环,不使用缓存,边读边写
//                    while ((fis.read(in)) > 0) {
//                        fos.write(in);
//                    }
                    while ((bis.read(in)) != -1) {
                        bos.write(in);
                    }
                    bos.close();
                    bis.close();
                    fos.close();
                    fis.close();
                    Log.i("CopyTime", System.currentTimeMillis() - before + "ms");
                    if (wfile.length() > 0) {     //文件大小不为空
                        Toast.makeText(getApplicationContext(), "文件复制成功", Toast.LENGTH_SHORT).show();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        //字符流读写文件
        bt4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    File ifile = new File("/mnt/sdcard/copy.txt");//目标文件
                    File wfile = new File("/mnt/sdcard/Test/copy1.txt");//复制文件
                    FileInputStream fis = new FileInputStream(ifile);
                    FileOutputStream fos = new FileOutputStream(wfile);
                    InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
                    OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
                    char input[] = new char[100];
                    int l = 0;//主要用来记录最后一次数组长短,写入文件;若不记录,char数组最后一次读取可能不足,将给文件写入多余或错误数据
                    while ((l = isr.read(input)) != -1) {
                        //String inputString = new String(input,0,l);
                        osw.write(input, 0, l);
                    }
                    isr.close();
                    fis.close();
                    osw.close();
                    fos.close();
                    if (wfile.length() > 0) {     //文件大小不为空
                        Toast.makeText(getApplicationContext(), "文件复制成功", Toast.LENGTH_SHORT).show();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        //FileReader、FileWriter直接读写文件,包装缓冲流进行拷贝
        bt5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    File ifile = new File("/mnt/sdcard/copy.txt");//目标文件
                    File wfile = new File("/mnt/sdcard/Test/copy2.txt");//复制文件
                    FileReader fr = new FileReader(ifile);
                    BufferedReader br = new BufferedReader(fr);
                    FileWriter fw = new FileWriter(wfile);
                    BufferedWriter bw = new BufferedWriter(fw);
                    String line;
                    while ((line = br.readLine()) != null) {
                        bw.write(line + "\n");
                    }
                    bw.flush();//强制将缓冲流输出
                    bw.close();
                    fw.close();
                    br.close();
                    fr.close();
                    if (wfile.length() > 0) {     //文件大小不为空
                        Toast.makeText(getApplicationContext(), "文件复制成功", Toast.LENGTH_SHORT).show();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        //RandomAccessFile随机读取,适用多线程下载等操作
        bt6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = new File("/mnt/sdcard/RandomAccessFile随机读取.txt");//目标文件
                //打乱线程順序不影响文件块写入
                new WriteFile(file, 5).start();
                new WriteFile(file, 3).start();
                new WriteFile(file, 1).start();
                new WriteFile(file, 4).start();
                new WriteFile(file, 2).start();
//                    RandomAccessFile raf = new RandomAccessFile(file, "r");//以只读方式打开文件
//                    raf.seek(300);
//                    byte[] str = new byte[20];
//                    raf.read(str);
//                    String in = new String(str);
//                    Log.i("RandomAccessFile随机读取",in);
                Toast.makeText(getApplicationContext(), "文件写入成功", Toast.LENGTH_SHORT).show();
            }
        });
        //通过调用Apache IO的jar包,快捷实现文件的操作
        bt7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    File file1 = new File("/mnt/sdcard/copy.txt");//目标文件
                    File file2 = new File("/mnt/sdcard/Apache IO Copy.txt");//目标文件
//                String input = FileUtils.readFileToString(file1, "UTF-8");//读取文件内容
                    FileUtils.copyFile(file1, file2);
                    Toast.makeText(getApplicationContext(), "文件复制成功", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        
    }
}

WriteFile.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class WriteFile extends Thread {
    File file;
    int block;//块
    int L = 5;//块大小
    /**
     * File        数据插入文件
     *            |***        |+++
     * |-----------***---------+++--------------------------|
     *      |---
     */
    /**
     * 文件块示意图
     * 1            2            3            4            5
     * |------------|------------|------------|------------|------------|
     * 0xL          1xL
     *
     * @param f
     * @param b
     */
    public WriteFile(File f, int b) {
        this.file = f;
        this.block = b;
    }
    @Override
    public void run() {
        try {
            RandomAccessFile raf = new RandomAccessFile(file, "rw");//rw代表可读可写,参数还有r、rws、rwd
            raf.seek((block - 1) * L);//定位指针
            raf.writeBytes("abcde" + block);
            /**
             * 注:如果写入数据小于块大小,未填满数据块,多余字节位置大小依然存在(虽然不一定可见)
             * 若数据大于块大小,将占用后面块的位置,后写入的块数据从块指定位置开始,又会重叠在后方块之上
             */
//            for (int i = 0; i < 20; i++) {
//                raf.writeBytes("-");
//            }
            raf.writeBytes("\n");//会占用一个字节的位置大小
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.administrator.filetestapplacation.MainActivity">
    <EditText
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:hint="请输入文本信息"/>
    <Button
        android:id="@+id/save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="保存文本"/>
    <Button
        android:id="@+id/write"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="输出文本"/>
    <EditText
        android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:hint="输出文本信息"/>
    <Button
        android:id="@+id/copy"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Copy by 缓冲字节流" />
    <Button
        android:id="@+id/copy1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Copy by 字符流" />
    <Button
        android:id="@+id/copy2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Copy by File字符流" />
    <Button
        android:id="@+id/copy3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="RandomAccessFile随机读取" />
    <Button
        android:id="@+id/copy4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Apache IO Copy" />
</LinearLayout>

注:需导入Apache IO包

前两个按钮效果图(未完整版):

incomplete photo.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容