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包
前两个按钮效果图(未完整版):