java IO文件操作
文件的读写尽量使用可缓冲的输入输出流。好处是:使用可缓存的输入输出流,减少了读写文件的次数,可以提升IO的性能,特别是遇到文件非常大时,效率会得到显著提升。
public class IoTest { public static void main(String[] args) { BufferedInputStream bis = null; BufferedOutputStream bos = null; FileInputStream fis = null; FileOutputStream fos = null; try { File srcFile = new File("/test1/1.txt"); File destFile = new File("/test1/2.txt"); fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); byte[] buffer = new byte[1024]; int len; while ((len = bis.read(buffer)) != -1) { bos.write(buffer, 0, len);//将从偏移量0开始的指定字节数组buffer中的 len字节写入此缓冲输出流。 } bos.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (bos != null) { bos.close(); } if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (bis != null) { bis.close(); } if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } } } 【1】145ms File file = new File(new File("").getAbsoluteFile()+File.separator+"demo.txt"); Writer writer = new FileWriter(file); long begin = System.currentTimeMillis(); for(int i=0;i<1000000;i++) { writer.write(i); } writer.close(); long end = System.currentTimeMillis(); System.out.println(end - begin); 【2】86ms File file = new File(new File("").getAbsoluteFile()+File.separator+"demo.txt"); Writer writer = new BufferedWriter(new FileWriter(file)); long begin = System.currentTimeMillis(); for(int i=0;i<1000000;i++) { writer.write(i); } writer.close(); long end = System.currentTimeMillis(); System.out.println(end - begin);
Android 读写设备节点值
private void writeToFile(String value) { FileWriter fw = null; try { fw = new FileWriter("/sys/class/leds/backlight/brightness"); fw.write(value); fw.close(); } catch (IOException e) { Log.i("androidos.net", "one problem has occured!"); } } private void writeToLed(String cmd){ try { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("/sys/class/leds/backlight/brightness")); }catch (IOException e){ e.printStackTrace(); } } private void writeValesToSysFile(String cmd) { final File file = new File("/sys/class/leds/backlight/brightness"); FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(cmd.getBytes()); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
//读节点 BufferedReader reader = new BufferedReader(new FileReader(PATH)); String info = reader.readLine(); //写节点 FileOutputStream fileOutputStream = new FileOutputStream(PATH); fileOutputStream.write(str.getBytes()); fileOutputStream.close(); //写节点 Write write = new FileWriter(PATH) write.write("androdios.net"); write.flush(); write.close();
[1]读取文件内容
复制文件[1]
private void appendFile (File copyFrom,File writeTo) { try { BufferedReader in = new BufferedReader(new FileReader(copyFrom)); FileWriter out = new FileWriter(writeTo, true);//true表示在现有文件加追加,false表示覆盖 String line = null; // Write line-by-line from "copyFrom" to "writeTo" while ((line = in.readLine()) != null) { out.write(line); out.write('\n'); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
用字节流读取转换成字符流并指定文件编码
示例1 try { FileInputStream fstream = new FileInputStream(filename); InputStreamReader reader = new InputStreamReader(fstream, "UTF-8"); // Got it... copy the stream into a local string and return it. final StringBuilder builder = new StringBuilder(128); char[] buffer = new char[8192]; int len; while ((len=reader.read(buffer)) > 0) { builder.append(buffer, 0, len); } return builder.toString(); } catch (IOException e) { // Something bad has happened. Log.w("ClipData", "Failure loading text", e); return e.toString(); } 示例2 private String getPsStat(String psname) { String stat = ""; try { FileInputStream fs = new FileInputStream("/proc" + psname + "/stat"); BufferedReader br = new BufferedReader(new InputStreamReader(fs)); stat = br.readLine(); fs.close(); } catch (IOException e) { Log.d(TAG, "Error retreiving stat. \n"); } return stat; } 示例3 BufferedReader reader = new BufferedRead(new InputStreamRead(new FileInputStream(filepath ,"gbk"))); String line; while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); }
【2】保存文件
使用BufferedWrite保存文件
private void writeResults() { // write result into a file File externalStorage = Environment.getExternalStorageDirectory(); if (!externalStorage.canWrite()) { Log.v(TAG, "sdcard is not writable"); return; } File resultFile = new File(externalStorage, RESULT_FILE); resultFile.setWritable(true, false); try { BufferedWriter rsWriter = new BufferedWriter(new FileWriter(resultFile)); writer.write("androidos.net"); writer.flush(); }catch(IOException e){ } }
示例2
private void writeResults() { BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF-8), 32 * 1024); out.write("DONE."); out.newLine(); } catch (Exception e) { //.... } finally { if (out != null) { out.close(); } } }
文件复制:当逐行读写大于2G的文本文件时推荐使用以下代码
void largeFileIO(String inputFile, String outputFile) { try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(inputFile))); BufferedReader in = new BufferedReader(new InputStreamReader(bis, "utf-8"), 10 * 1024 * 1024);//10M缓存 FileWriter fw = new FileWriter(outputFile); while (in.ready()) { String line = in.readLine(); fw.append(line + " "); } in.close(); fw.flush(); fw.close(); } catch (IOException ex) { ex.printStackTrace(); }
超大文件的读写一类是使用BufferedReader类读写超大文件;另一类是使用RandomAccessFile类读取,经过比较,最后使用了前一种方式进行超大文件的读取,下面是相关代码,其实很简单
File file = new File(filepath); BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file)); BufferedReader reader = new BufferedReader(new InputStreamReader(fis,"utf-8"),5*1024*1024);// 用5M的缓冲读取文本文件 String line = ""; while((line = reader.readLine()) != null){ //TODO: write your business }
将File文件内容转换成String
private String fileToString(File file) { final String newline = System.lineSeparator(); try { BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuffer sb = new StringBuffer((int) file.length() * 2); String line; while ((line = reader.readLine()) != null) { sb.append(line + newline); } reader.close(); return sb.toString(); } catch (IOException ioe) { Slog.e(TAG, "Couldn't read file " + file.getName()); return null; } }
java获取文件的行数:
public static int getFileLines(final File file) { int count = 1; InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[1024]; int readChars; if (LINE_SEP.endsWith("\n")) { while ((readChars = is.read(buffer, 0, 1024)) != -1) { for (int i = 0; i < readChars; ++i) { if (buffer[i] == '\n') ++count; } } } else { while ((readChars = is.read(buffer, 0, 1024)) != -1) { for (int i = 0; i < readChars; ++i) { if (buffer[i] == '\r') ++count; } } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } return count; }
FileUtil.java工具类:https://github.com/Blankj/AndroidUtilCode/blob/a8c82701168f7143ec4c90dabe10c7c8faa77e9a/lib/utilcode/src/main/java/com/blankj/utilcode/util/FileUtils.java#L51
FileUtil.java类
package com.sky.xposed.rimet.util; import android.content.Context; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.text.TextUtils; import com.sky.xposed.common.util.Alog; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File;import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.text.DecimalFormat; import java.util.ArrayList;import java.util.List;/** * Created by starrysky on 16-4-19. */public class FileUtil { public static final String TAG = "FileUtil"; private static final Object lock = new Object(); /** * 将日志写入文件。 * @param message * @param tr */ public static void writeLog(File logFile, String message, Throwable tr) { synchronized (lock) { FileWriter fileWriter = null; BufferedWriter bufdWriter = null; PrintWriter printWriter = null; try { File dir = logFile.getParentFile(); if (!dir.exists()) dir.mkdir(); fileWriter = new FileWriter(logFile, false); bufdWriter = new BufferedWriter(fileWriter); printWriter = new PrintWriter(fileWriter); // 添加头部信息 bufdWriter.append(message); bufdWriter.flush(); tr.printStackTrace(printWriter); printWriter.append("\n\n"); printWriter.flush(); fileWriter.flush(); } catch (IOException e) { FileUtil.closeQuietly(fileWriter); FileUtil.closeQuietly(bufdWriter); FileUtil.closeQuietly(printWriter); } } } /** * 获取Assets目录下的文件内容(默认是UTF-8编码) * @param context * @param name * @return */ public static String getAssetsContent(Context context, String name) { InputStream inputStream = null; AssetManager assetManager = context.getAssets(); try { inputStream = assetManager.open(name); return new String(readContent(inputStream)); } catch (Exception e) { Alog.e(TAG, "获取Assets数据异常!", e); } finally { closeQuietly(inputStream); } return null; } /** * 获取Assets目录下的图片 * @param context * @param name * @return */ public static Bitmap getAssetsImage(Context context, String name) { InputStream inputStream = null; AssetManager assetManager = context.getAssets(); try { inputStream = assetManager.open(name); // 获取图标 return BitmapFactory.decodeStream(inputStream); } catch (Exception e) { Alog.e(TAG, "获取Assets数据异常!", e); } finally { closeQuietly(inputStream); } return null; } /** * 读取指定文件中的内容并以byte数组形式的返回文件内容 * @param source 读取的文件路径 * @return 读取的文件内容 */ public static byte[] readFile(File source) { FileInputStream in = null; ByteArrayOutputStream out = null; try { in = new FileInputStream(source); // 缓冲大小使用文件大小 out = new ByteArrayOutputStream((int) source.length()); int len; byte[] buffer = new byte[4096]; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } return out.toByteArray(); } catch (Exception e) { Alog.e(TAG, "获取文件信息异常", e); } finally { closeQuietly(out); closeQuietly(in); } return null; } /** * 把指定的byte数组内容保存到指定路径的文件中 * @param target 保存的文件路径 * @param content 需要保存的内容 * @throws IOException */ public static boolean writeFile(File target, byte[] content) { if (target == null || content == null) return false; File parent = target.getParentFile(); if (!parent.isDirectory()) parent.mkdirs(); FileOutputStream out = null; try { out = new FileOutputStream(target); out.write(content); out.flush(); return true; } catch (Exception e) { Alog.e(TAG, "写文件信息异常", e); } finally { closeQuietly(out); } return false; } /** * 把指定的内容保存到指定路径的文件中 * @param target 保存的文件路径 * @param content 需要保存的内容 */ public static boolean writeFile(File target, String content, String charsetName) { if (TextUtils.isEmpty(content)) return false; if (TextUtils.isEmpty(charsetName)) charsetName = "UTF-8"; try { // 保存信息到本地 return writeFile(target, content.getBytes(charsetName)); } catch (UnsupportedEncodingException e) { Alog.e(TAG, "文本编码异常", e); } return false; } public static boolean copyFile(File source, File target) { if (source == null || !source.exists() || target == null) return false; File parent = target.getParentFile(); if (!parent.isDirectory()) parent.mkdirs(); FileInputStream in = null; FileOutputStream out = null; try { int length; byte[] buffer = new byte[2048]; in = new FileInputStream(source); out = new FileOutputStream(target); while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } out.flush(); return true; } catch (Exception e) { Alog.e(TAG, "复制文件信息异常", e); } finally { closeQuietly(out); closeQuietly(in); } return false; } /** * 把指定的内容保存到指定路径的文件中(默认UTF-8类型) * @param target 保存的文件路径 * @param content 需要保存的内容 */ public static boolean writeFile(File target, String content) { // 保存信息到本地 return writeFile(target, content, "UTF-8"); } /** * 读取文件内容(默认的编码方式UTF-8) * @param file * @return */ public static String readContent(File file) { return readContent(file, "UTF-8"); } public static String readContent(File file, String charsetName) { if (file == null || !file.isFile()) return null; if (TextUtils.isEmpty(charsetName)) charsetName = "UTF-8"; try { return new String(readFile(file), charsetName); } catch (Exception e) { Alog.e(TAG, "读取文件数据异常!", e); } return null; } public static List<String> readContentToList(File source) { if (source == null || !source.isFile()) return null; FileInputStream in = null; BufferedReader br = null; List<String> lines = new ArrayList<>(); try { in = new FileInputStream(source); br = new BufferedReader(new InputStreamReader(in)); String line; while ((line = br.readLine()) != null) { lines.add(line); } return lines; } catch (Exception e) { Alog.e(TAG, "获取文件信息异常", e); } finally { closeQuietly(br); closeQuietly(in); } return null; } public static byte[] readContent(InputStream in) throws IOException { ByteArrayOutputStream baos = null; try { int len; byte[] buffer = new byte[1024]; baos = new ByteArrayOutputStream(1024); while ((len = in.read(buffer)) != -1) { baos.write(buffer, 0, len); } return baos.toByteArray(); } finally { if (baos != null) baos.close(); } } public static void closeQuietly(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException ioe) { // ignore } } } public static void delete(File file) { if (file == null || !file.exists()) return ; try { // 删除文件 file.delete(); } catch (Exception e) { Alog.e(TAG, "删除文件失败"); } } public static void deleteDir(File dir) { if (dir == null || !dir.exists()) return ; File[] files = dir.listFiles(); if (files == null) return ; for (File file : files) { // 删除文件 delete(file); } // 删除目录 delete(dir); } /** * 创建文件 * @param file * @return */ public static boolean createFile(File file) { if (file == null) return false; if (file.isFile()) return true; // 创建目录 createDir(file.getParentFile()); try { return file.createNewFile(); } catch (IOException e) { Alog.e("CreateNewFile Exception", e); } return false; } /** * 创建文件目录 * @param file * @return */ public static boolean createDir(File file) { return file != null && file.mkdirs(); } public static boolean exists(File file) { return file != null && file.exists(); } public static boolean exists(String dir, String name) { return exists(new File(dir, name)); } private static final DecimalFormat DF = new DecimalFormat("0.00"); public static String getDownloadPerSize(long finished, long total) { return DF.format((float) finished / (1024 * 1024)) + "MB/" + DF.format((float) total / (1024 * 1024)) + "MB"; } /** * 检查文件时候存在,不存在就创建 * @param file */ public static void checkOrCreateEmptyFile(File file) { if (!file.exists()) { file.getParentFile().mkdirs(); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } }}
File操作关联文章:
java 获取目录下所有文件及文件目录
版权声明:如无特殊标注,文章均为本站原创,转载时请以链接形式注明文章出处。
评论