向android中写文件
2014-04-01 10:45
281 查看
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class WriteFile { //创建和写文件 private static String path = "/sdcard/"; private static String filenameTemp; /** * 创建文件 * * @throws IOException */ public static boolean creatTxtFile(String name) throws IOException { boolean flag = false; filenameTemp = path + name + ".txt"; File filename = new File(filenameTemp); if (!filename.exists()) { filename.createNewFile(); flag = true; } return flag; } /** * 写文件 * * @param newStr * 新内容 * @throws IOException */ public static boolean writeTxtFile(String newStr) throws IOException { // 先读取原有文件内容,然后进行写入操作 boolean flag = false; String filein = newStr + "\r\n"; String temp = ""; FileInputStream fis = null; InputStreamReader isr = null; BufferedReader br = null; FileOutputStream fos = null; PrintWriter pw = null; try { // 文件路径 File file = new File(filenameTemp); // 将文件读入输入流 fis = new FileInputStream(file); isr = new InputStreamReader(fis); br = new BufferedReader(isr); StringBuffer buf = new StringBuffer(); // 保存该文件原有的内容 for (int j = 1; (temp = br.readLine()) != null; j++) { buf = buf.append(temp); // System.getProperty("line.separator") // 行与行之间的分隔符 相当于“\n” buf = buf.append(System.getProperty("line.separator")); } buf.append(filein); fos = new FileOutputStream(file); pw = new PrintWriter(fos); pw.write(buf.toString().toCharArray()); pw.flush(); flag = true; } catch (IOException e1) { // TODO 自动生成 catch 块 throw e1; } finally { if (pw != null) { pw.close(); } if (fos != null) { fos.close(); } if (br != null) { br.close(); } if (isr != null) { isr.close(); } if (fis != null) { fis.close(); } } return flag; } }在其他类中调用方法
private void writeFile() {// TODO Auto-generated method stubWriteFile myFile = new WriteFile();try {myFile.creatTxtFile("文件名");Date now=new Date();SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String name = dateFormat.format(now);//写入的信息myFile.writeTxtFile(name+","+lac+","+plot1.getText()+","+longitude+","+latitude+","+currentsingle);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
相关文章推荐
- [转]Android Recovery汉化
- android创建提示音
- 【转】android 电容屏(三):驱动调试之驱动程序分析篇
- android--OpenCV--环境搭建
- 【Handler】在Android中使用Handler和Thread线程执行后台操作
- android判断当前应用程序处于前台还是后台
- 【转】android 电容屏(二):驱动调试之基本概念篇
- Android Sqlite Upgrade
- 我认为是安卓的一个bug,吐槽一下
- 从android选取文件获取文件路径,并将文件读入到数据库中,有进度条显示
- 【转】android 电容屏(一):电容屏基本原理篇
- Android中的尺寸单位2
- Android Activity之间的跳转
- Android TextView走马灯效果
- Handler Looper源码解析(Android消息传递机制)
- Android组件学习之TextView的直接子类和间接子类
- 【Internet】android.os.NetworkOnMainThreadException问题
- android Toast 消息提示 例子
- VisionMobile:剥光Android
- XML - Android中解析XML