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(,))){
fileUrl = (fileUrl.substring(,fileUrl.length()-));//linux
}else{
fileUrl = (fileUrl.substring(,fileUrl.length()-));//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)!=-){
arrayStr = str.split(splitStr);
}else{
arrayStr = new String[];
arrayStr[] = 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", "");
}else{
boolean flag = f.isDirectory();
if(flag==false){ //路径为文件
map.put("retType", "");
map.put("fileName", f.getName());
}else{ //路径为文件夹
map.put("retType", "");
File fa[] = f.listFiles();
queryStr = queryStr==null ? "" : queryStr;//若queryStr传入为null,则替换为空(indexOf匹配值不能为null)
for (int i = ; i < fa.length; i++) {
File fs = fa[i];
if(fs.getName().indexOf(queryStr)!=-){
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 = ;
// 一次读入一行,直到读入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=;
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 = ;
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 = ;
// 一次读入一行,直到读入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[ * ];
try {
int cnt = ins.read(bb);
while (cnt > ) {
out.write(bb, , 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 == 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();
} }
java简单的文件读写工具类的更多相关文章
- properties文件读写工具类
java代码: import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; ...
- Spring-Boot ☞ ShapeFile文件读写工具类+接口调用
一.项目目录结构树 二.项目启动 三.往指定的shp文件里写内容 (1) json数据[Post] { "name":"test", "path&qu ...
- android 文件读写工具类
将可以序列化的对象通过base64编码后进行保存 但是感觉多数情况下,不需要采用这个功能,直接保存原始的json字符串,取出来之后再进行解析即可 package com.wotlab.home.mon ...
- list集合、txt文件对比的工具类和文件读写工具类
工作上经常会遇到处理大数据的问题,下面两个工具类,是在处理大数据时编写的:推荐的是使用map的方式处理两个list数据,如果遇到list相当大数据这个方法就起到了作用,当时处理了两个十万级的list, ...
- java文件读写工具类
依赖jar:commons-io.jar 1.写文件 // by FileUtilsList<String> lines = FileUtils.readLines(file, " ...
- Java操作属性文件之工具类
最近空闲时间整理一下平时常用的一下工具类,重复造轮子实在是浪费时间,如果不正确或者有待改善的地方,欢迎指教... package com.hsuchan.business.utils; import ...
- properties文件读写工具类PropertiesUtil.java
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import ...
- java IO Nio 文件拷贝工具类Files
public static void main(String[] args) throws Exception { Files.copy(Paths.get("file/text.txt&q ...
- 文件类型工具类:FileTypeUtil
个人学习,仅供参考! package com.example.administrator.filemanager.utils;import java.io.File;/** * 文件类型工具类 * * ...
随机推荐
- 03bootstrap_表格
03bootstrap_表格 1.边框线表格:table,table-striped,table-bordered 2.紧缩表格:table table-hover table-condensed 文 ...
- zabbix的自动发现、自定义添加监控项目、配置邮件告警
1.zabbix的自动发现这里的自动发现,所显示出来的是规则的上自动了现 然后 可以对其内容进行相关的配制,如时间或周期 注意:对于单个主机的规则,可以自行添加或删除, 但对于已经添加好了的规则,若需 ...
- 《DSP using MATLAB》Problem 7.13
代码: %% ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ %% Output In ...
- oracle命令1
基础查询 查询当前用户 show user; 查询当前用户下的表 select * from tab; 清屏 host cls: clear; --查询所有的员工信息 select * from e ...
- PS 给照片换背景
1. 打开一张照片,导入证件照 2. 点击选择 => 选择并遮住 (快捷键 command + option + r) 3. 点击快速选择工具,将属性设置里面的视图模式选择为洋葱皮,鼠标点击需要 ...
- System.Object
Object():System.Object类型的构造函数,自动调用. ~Object()/Finalize():System.Object类型的祈构函数,自动调用且不能够手动. Equals(obj ...
- 将Long类型转为字母数字组合的jar包---Hashids
在设计数据库时,我有时喜欢使用自增Id,而不是uuid,但是在面对终端用户时,直接暴露id不是一个好的行为. 经过查询,可以使用 Hashids 这个jar包将id转为类似YouTube的大小写字母和 ...
- note 3 变量与简单I/O
变量(Variable) 用于引用(绑定对象的标识符) 语法 变量名=对象(数值.表达式等) 增量赋值运算符 count = count + 1 简写 count += 1 标识符(Identifie ...
- 微信小程序如何设置服务器配置
最近微信小程序在it界火了起来,公司也要求我们开始接触微信小程序,废话不多说直接从配置微信小程序开始 1,首先,登录 https://mp.weixin.qq.com,(这里默认你已经获取到微信小程序 ...
- lecune入门示例
注意:本示例中的lucene版本需在jdk7以上使用. 一.pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" ...