安卓如何将TXT文件写到特定路径
其实就一个方法,就不贴所有代码了。
/** * 写入文件方法 * @param content */ public static void write(String content) { try { //判断实际是否有SD卡,且应用程序是否有读写SD卡的能力,有则返回true if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { // 获取SD卡的目录 File sdCardDir = Environment.getExternalStorageDirectory(); String path = "/APP/"; File dir = new File(sdCardDir+path); if (!dir.exists()) { dir.mkdirs(); } File targetFile = new File(sdCardDir.getCanonicalPath() + path+"aaa.txt"); //使用RandomAccessFile是在原有的文件基础之上追加内容, //而使用outputstream则是要先清空内容再写入 RandomAccessFile raf = new RandomAccessFile(targetFile, "rw"); //光标移到原始文件最后,再执行写入 raf.seek(targetFile.length()); raf.write(content.getBytes()); raf.close(); } } catch (Exception e) { e.printStackTrace(); } }
package com.example.linfeng.myapplication; import android.os.Environment; import java.io.File; import java.io.RandomAccessFile; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by LinFeng on 2017/11/13. */ public class TextHelper { public static void write(String content, String PathName, String FileName) { try { //判断实际是否有SD卡,且应用程序是否有读写SD卡的能力,有则返回true if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { // 获取SD卡的目录 File sdCardDir = Environment.getExternalStorageDirectory(); //Log.i("paht",sdCardDir.toString()); String path = "/" + PathName + "/"; //如果不存在,就创建目录 File dir = new File(sdCardDir + path); if (!dir.exists()) { dir.mkdirs(); } File targetFile = new File(sdCardDir.getCanonicalPath() + path + FileName + ".dat"); //使用RandomAccessFile是在原有的文件基础之上追加内容, //而使用outputstream则是要先清空内容再写入 RandomAccessFile raf = new RandomAccessFile(targetFile, "rw"); //光标移到原始文件最后,再执行写入 raf.seek(targetFile.length()); raf.write(content.getBytes()); raf.close(); } } catch (Exception e) { e.printStackTrace(); } } //写头文件,如果不存在写,存在就不写 public static void writeHead(String path,String fileName,char type){ String string=Environment.getExternalStorageDirectory()+"/" + path + "/"+fileName+".dat"; if (!fileIsExists(string)){ switch (type){ case 'I': String content = "Type=Inventory"+"\r\n"+"Date="+getStringDate()+"\r\n"+"ScannerNo=01"; write(content,path,fileName); break; case 'M': write("Type=Market"+"\r\n",path,fileName); break; case 'R': write("Type=Return"+"\r\n",path,fileName); break; } }else{ } } //判断文件是否存在 public static boolean fileIsExists(String strFile) { try { File f = new File(strFile); if (!f.exists()) { return false; } } catch (Exception e) { return false; } return true; } //获取当前时间,格式为:yyyyMMdd HH:mm:ss public static String getStringDate() { Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HH:mm:ss"); String dateString = formatter.format(currentTime); return dateString; } }