码迷,mamicode.com
首页 > 其他好文 > 详细

文件写操作

时间:2015-10-08 18:26:22      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:file 文件

文件的写操作
1、先判断SD卡是否存在
2、多级文件存储,先判断父文件夹是否存在,不存在则创建
3、文件读写操作是耗时的,所以最好放在线程里进行。

package com.exam.file;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import com.exam.util.CommandTools;
import android.os.Environment;
/**
 * 
 *
 * @author yxx
 *
 * 2015-10-8
 */
public class FileUtil {
/**
 * 判断手机是否有SD卡。
 * 
 * @return 有SD卡返回true,没有返回false。
 */
public static boolean existSDCard() {
return Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState());
} 
public static void writeToFile(String data) {
File file = new File(Environment.getExternalStorageDirectory(), "data.csv");//根目录下
OutputStream os = null;
try {
os = new FileOutputStream(file.getAbsoluteFile(),true);//true 为添加 不覆盖
os.write(data.getBytes());
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
 * 判断文件夹是否存在,
 * 不存在,自动创建
 * @param data
 */
public void write(String data){
File folder = new File(Environment.getExternalStorageDirectory() + "/alarm");
OutputStream os = null;
if(!folder.exists()){// 如果文件夹不存在,创建一个
folder.mkdirs(); //这里要用.mkdirs()方法,父类文件夹不存在时,可以自动创建
}                  //而如果用.mkdir()方法则不会自动创建
File file = new File(folder.getAbsolutePath(), "alarm.txt");
try {
os = new FileOutputStream(file,false);//true 为添加 不覆盖
os.write(data.getBytes());
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


new Thread(new Runnable() {

    @Override
    public void run() {
    
            String msg = "test file";
            FileUtil.writeToFile(msg);
	}
}).start();

本文出自 “爬过山见过海” 博客,请务必保留此出处http://670176656.blog.51cto.com/4500575/1700956

文件写操作

标签:file 文件

原文地址:http://670176656.blog.51cto.com/4500575/1700956

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!