当前位置: 移动技术网 > IT编程>开发语言>Java > java文件读写工具类分享

java文件读写工具类分享

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了java文件读写工具类的具体代码,供大家参考,具体内容如下

import java.io.bufferedinputstream;
import java.io.bufferedoutputstream;
import java.io.bufferedreader;
import java.io.file;
import java.io.fileinputstream;
import java.io.filereader;
import java.io.filewriter;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.io.printwriter;
import java.net.urlencoder;
import java.util.arraylist;
import java.util.calendar;
import java.util.date;
import java.util.hashmap;
import java.util.hashset;
import java.util.list;

import javax.servlet.http.httpservletresponse;

/**
 * <p>文件操作工具类<p>
 * @version 1.0
 * @author li_hao
 * @date 2017年1月18日
 */
@suppresswarnings({"resource","unused"})
public class fileutils {
  
  /**
   * 获取windows/linux的项目根目录
   * @return
   */
  public static string getcontextpath(){
    string fileurl = thread.currentthread().getcontextclassloader().getresource("").getpath();
    if("usr".equals(fileurl.substring(1,4))){
      fileurl = (fileurl.substring(0,fileurl.length()-16));//linux
    }else{
      fileurl = (fileurl.substring(1,fileurl.length()-16));//windows
    }
    return fileurl;
  }
    
  /**
   * 字符串转数组
   * @param str 字符串
   * @param splitstr 分隔符
   * @return
   */
  public static string[] stringtoarray(string str,string splitstr){
    string[] arraystr = null;
    if(!"".equals(str) && str != null){
      if(str.indexof(splitstr)!=-1){
        arraystr = str.split(splitstr);
      }else{
        arraystr = new string[1];
        arraystr[0] = str;
      }
    }
    return arraystr;
  }
    
  /**
   * 读取文件
   * 
   * @param path
   * @return
   */
  public static string readfile(string path) {
    bufferedreader reader = null;
    string laststr = "";
    try {
      fileinputstream fileinputstream = new fileinputstream(path);
      inputstreamreader inputstreamreader = new inputstreamreader(fileinputstream, "utf-8");
      reader = new bufferedreader(inputstreamreader);
      string tempstring = null;
      while ((tempstring = reader.readline()) != null) {
        laststr += tempstring;
      }
      reader.close();
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
    }
    return laststr;
  }
    
  /**
   * 获取文件夹下所有文件的名称 + 模糊查询(当不需要模糊查询时,querystr传空或null即可)
   * 1.当路径不存在时,map返回rettype值为1
   * 2.当路径为文件路径时,map返回rettype值为2,文件名filename值为文件名
   * 3.当路径下有文件夹时,map返回rettype值为3,文件名列表filenamelist,文件夹名列表foldernamelist
   * @param folderpath 路径
   * @param querystr 模糊查询字符串
   * @return
   */
  public static hashmap<string, object> getfilesname(string folderpath , string querystr) {
    hashmap<string, object> map = new hashmap<>();
    list<string> filenamelist = new arraylist<>();//文件名列表
    list<string> foldernamelist = new arraylist<>();//文件夹名列表
    file f = new file(folderpath);
    if (!f.exists()) { //路径不存在
      map.put("rettype", "1");
    }else{
      boolean flag = f.isdirectory();
      if(flag==false){ //路径为文件
        map.put("rettype", "2");
        map.put("filename", f.getname());
      }else{ //路径为文件夹
        map.put("rettype", "3");
        file fa[] = f.listfiles();
        querystr = querystr==null ? "" : querystr;//若querystr传入为null,则替换为空(indexof匹配值不能为null)
        for (int i = 0; i < fa.length; i++) {
          file fs = fa[i];
          if(fs.getname().indexof(querystr)!=-1){
             if (fs.isdirectory()) {
               foldernamelist.add(fs.getname());
             } else {
               filenamelist.add(fs.getname());
             }
           }
        }
        map.put("filenamelist", filenamelist);
        map.put("foldernamelist", foldernamelist);
      }
    }
    return map;
  }
  
  /**
   * 以行为单位读取文件,读取到最后一行
   * @param filepath
   * @return
   */
  public static list<string> readfilecontent(string filepath) { 
    bufferedreader reader = null;
    list<string> listcontent = new arraylist<>();
    try { 
      reader = new bufferedreader(new filereader(filepath)); 
      string tempstring = null; 
      int line = 1; 
      // 一次读入一行,直到读入null为文件结束 
      while ((tempstring = reader.readline()) != null) {
        listcontent.add(tempstring);
        line++;
      } 
      reader.close(); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } finally { 
      if (reader != null) { 
        try { 
          reader.close(); 
        } catch (ioexception e1) { 
        } 
      } 
    }
    return listcontent;
  } 
  
  /**
   * 读取指定行数据 ,注意:0为开始行
   * @param filepath
   * @param linenumber
   * @return
   */
  public static string readlinecontent(string filepath,int linenumber){
    bufferedreader reader = null;
    string linecontent="";
    try {
      reader = new bufferedreader(new filereader(filepath));
      int line=0;
      while(line<=linenumber){
        linecontent=reader.readline();
        line++;
      }
      reader.close();
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } finally { 
      if (reader != null) { 
        try { 
          reader.close(); 
        } catch (ioexception e1) { 
        } 
      } 
    } 
    return linecontent;
  }
  
  /**
   * 读取从beginline到endline数据(包含beginline和endline),注意:0为开始行
   * @param filepath
   * @param beginlinenumber 开始行
   * @param endlinenumber 结束行
   * @return
   */
  public static list<string> readlinescontent(string filepath,int beginlinenumber,int endlinenumber){
    list<string> listcontent = new arraylist<>();
    try{
      int count = 0;
    bufferedreader reader = new bufferedreader(new filereader(filepath));
      string content = reader.readline();
      while(content !=null){
        if(count >= beginlinenumber && count <=endlinenumber){
          listcontent.add(content);
        }  
        content = reader.readline();
        count++;  
      }
    } catch(exception e){
    }
    return listcontent;
  }
    
  /**
   * 读取若干文件中所有数据
   * @param listfilepath
   * @return
   */
  public static list<string> readfilecontent_list(list<string> listfilepath) { 
    list<string> listcontent = new arraylist<>();
    for(string filepath : listfilepath){
       file file = new file(filepath);
       bufferedreader reader = null;
      try { 
        reader = new bufferedreader(new filereader(file)); 
        string tempstring = null; 
        int line = 1; 
        // 一次读入一行,直到读入null为文件结束 
        while ((tempstring = reader.readline()) != null) {
          listcontent.add(tempstring);
          line++;
        } 
        reader.close(); 
      } catch (ioexception e) { 
        e.printstacktrace(); 
      } finally { 
        if (reader != null) { 
          try { 
            reader.close(); 
          } catch (ioexception e1) { 
          } 
        } 
      }
    }
    return listcontent;
  }
  
  /**
   * 文件数据写入(如果文件夹和文件不存在,则先创建,再写入)
   * @param filepath
   * @param content
   * @param flag true:如果文件存在且存在内容,则内容换行追加;false:如果文件存在且存在内容,则内容替换
   */
  public static string filelineswrite(string filepath,string content,boolean flag){
    string filedo = "write";
    filewriter fw = null;
    try {
      file file=new file(filepath);
      //如果文件夹不存在,则创建文件夹
      if (!file.getparentfile().exists()){
        file.getparentfile().mkdirs();
      }
      if(!file.exists()){//如果文件不存在,则创建文件,写入第一行内容
        file.createnewfile();
        fw = new filewriter(file);
        filedo = "create";
      }else{//如果文件存在,则追加或替换内容
        fw = new filewriter(file, flag);
      }
    } catch (ioexception e) {
      e.printstacktrace();
    }
      printwriter pw = new printwriter(fw);
      pw.println(content);
      pw.flush();
    try {
      fw.flush();
      pw.close();
      fw.close();
    } catch (ioexception e) {
      e.printstacktrace();
    }
    return filedo;
  }
      
  /**
   * 写文件
   * @param ins
   * @param out
   */
  public static void writeintoout(inputstream ins, outputstream out) {
    byte[] bb = new byte[10 * 1024];
    try {
      int cnt = ins.read(bb);
      while (cnt > 0) {
        out.write(bb, 0, cnt);
        cnt = ins.read(bb);
      }
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      try {
        out.flush();
        ins.close();
        out.close();
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
  }
  
  /**
   * 判断list中元素是否完全相同(完全相同返回true,否则返回false)
   * @param list
   * @return
   */
  private static boolean hassame(list<? extends object> list){ 
    if(null == list) 
      return false; 
    return 1 == new hashset<object>(list).size(); 
  } 
  
  /**
   * 判断list中是否有重复元素(无重复返回true,否则返回false)
   * @param list
   * @return
   */
  private static boolean hassame2(list<? extends object> list){ 
    if(null == list) 
      return false; 
    return list.size() == new hashset<object>(list).size(); 
  } 
  
  /**
   * 增加/减少天数
   * @param date
   * @param num
   * @return
   */
  public static date dateaddorsub(date date, int num) { 
    calendar startdt = calendar.getinstance(); 
    startdt.settime(date); 
    startdt.add(calendar.day_of_month, num); 
    return startdt.gettime(); 
  }
  
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网