(1)openFileInput和openFileOutput的使用
文件的使用,注意最后要用finally给关闭掉。
openFileOutput:(写入文件,如果没有文件名可以创建,这里不需要判断是否有这个文件)---> FileOutputStream
openFileInput:(读取文件,没有文件名会保存,debug的时候会看到,不影响ui)---> FileInputStream
保存文件:(FileOutputStream 保存地址;data/data/包名/files/, 下面是写入的四种模式)
MODE_APPEND:即向文件尾写入数据
MODE_PRIVATE:即仅打开文件可写入数据
MODE_WORLD_READABLE:所有程序均可读该文件数据
MODE_WORLD_WRITABLE:即所有程序均可写入数据。
private void savePackageFile() { //写入文件,filename可以只写文件名,不用完整路径
String msg = tvSaveMessage.getText().toString() + " \n";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_APPEND);
outputStream.write(msg.getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void readSaveFile() { //读取文件:(FileInputStream 读取包名下files文件夹下的文件)
FileInputStream inputStream;
try {
inputStream = openFileInput(filename);
byte temp[] = new byte[1024];
StringBuilder sb = new StringBuilder("");
int len = 0;
while ((len = inputStream.read(temp)) > 0){
sb.append(new String(temp, 0, len));
}
Log.d("msg", "readSaveFile: \n" + sb.toString());
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
File logFile = new File(context.getFilesDir(), MainActivity.filename); //文件的初始化:(创建需要的文件)
if (!logFile.exists()) { // Make sure log file is exists
boolean result; // 文件是否创建成功
try {
result = logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return;
}
if (!result) {
return;
}
}
(2)BufferReader和BufferWriter使用:
保存文件:如果没有会自动创建,如果有的话会覆盖。 当在创建时加入true参数,实现对文件的续写。 false则会覆盖前面的数据
public static void bufferSave(String msg) {
try {
BufferedWriter bfw = new BufferedWriter(new FileWriter(logFile, true));
bfw.write(msg);
bfw.newLine();
bfw.flush();
bfw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
读取文件:这里需要做判断,如果没有这个文件会报错。
public static void bufferRead() {
try {
BufferedReader bfr = new BufferedReader(new FileReader(logFile));
String line = bfr.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line);
sb.append("\n");
line = bfr.readLine();
}
bfr.close();
Log.d("buffer", "bufferRead: " + sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
(3)SD卡读取和写入—路径:/storage/sdcard0/
往SD卡写入文件的方法,如果手机已插入sd卡,且app具有读写sd卡的权限
public void savaFileToSD(String filename, String filecontent) throws Exception {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
FileOutputStream output = new FileOutputStream(filename); //这里就不要用openFileOutput了,那个是往手机内存中写数据的
output.write(filecontent.getBytes()); //将String字符串以字节流的形式写入到输出流中
output.close(); //关闭输出流
} else Toast.makeText(context, "SD卡不存在或者不可读写", Toast.LENGTH_SHORT).show();
}
读取SD卡中文件的方法,定义读取文件的方法:
public String readFromSD(String filename) throws IOException {
StringBuilder sb = new StringBuilder("");
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
FileInputStream input = new FileInputStream(filename); //打开文件输入流
byte[] temp = new byte[1024];
int len = 0;
while ((len = input.read(temp)) > 0) { //读取文件内容:
sb.append(new String(temp, 0, len));
}
input.close(); //关闭输入流
}
return sb.toString();
}
(4)读取raw和assets文件夹下的文件
res/raw:文件会被映射到R.java文件中,访问的时候直接通过资源ID即可访问,而且 他不能有目录结构,就是不能再创建文件夹
assets:不会映射到R.java文件中,通过AssetManager来访问,能有目录结构,即可以自行创建文件夹
读取文件资源;
raw:
InputStream is =getResources().openRawResource(R.raw.filename);
assets:
AssetManager am = getAssets();
InputStream is = am.open("filename");
一、首先添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
二、建立文件夹、生成文件并写入文本文件内容代码
private void initData() {
String filePath = "/sdcard/Test/";
String fileName = "log.txt";
writeTxtToFile("txt content", filePath, fileName);
}
// 将字符串写入到文本文件中
public void writeTxtToFile(String strcontent, String filePath, String fileName) {
makeFilePath(filePath, fileName); //生成文件夹之后,再生成文件,不然会出错
String strFilePath = filePath+fileName;
String strContent = strcontent + "\r\n"; // 每次写入时,都换行写
try {
File file = new File(strFilePath);
if (!file.exists()) {
Log.d("TestFile", "Create the file:" + strFilePath);
file.getParentFile().mkdirs();
file.createNewFile();
}
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(file.length());
raf.write(strContent.getBytes());
raf.close();
} catch (Exception e) {
Log.e("TestFile", "Error on write File:" + e);
}
}
// 生成文件
public File makeFilePath(String filePath, String fileName) {
File file = null;
makeRootDirectory(filePath);
try {
file = new File(filePath + fileName);
if (!file.exists()) {
file.createNewFile();
}
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
// 生成文件夹
public static void makeRootDirectory(String filePath) {
File file = null;
try {
file = new File(filePath);
if (!file.exists()) {
file.mkdir();
}
} catch (Exception e) {
Log.i("error:", e+"");
}
}