JAVA FileUtils(文件读写以及操作工具类)
文件操作常用功能:
package com.suning.yypt.business.report; import java.io.*;
import java.util.*; @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();
}
//https://www.cnblogs.com/chenhuan001/p/6575053.html
/**
* 递归删除文件或者目录
* @param file_path
*/
public static void deleteEveryThing(String file_path) {
try{
File file=new File(file_path);
if(!file.exists()){
return ;
}
if(file.isFile()){
file.delete();
}else{
File[] files = file.listFiles();
for(int i=0;i<files.length;i++){
String root=files[i].getAbsolutePath();//得到子文件或文件夹的绝对路径
deleteEveryThing(root);
}
file.delete();
}
} catch(Exception e) {
System.out.println("删除文件失败");
}
}
/**
* 创建目录
* @param dir_path
*/
public static void mkDir(String dir_path) {
File myFolderPath = new File(dir_path);
try {
if (!myFolderPath.exists()) {
myFolderPath.mkdir();
}
} catch (Exception e) {
System.out.println("新建目录操作出错");
e.printStackTrace();
}
} //https://blog.csdn.net/lovoo/article/details/77899627
/**
* 判断指定的文件是否存在。
*
* @param fileName
* @return
*/
public static boolean isFileExist(String fileName) {
return new File(fileName).isFile();
} /* 得到文件后缀名
*
* @param fileName
* @return
*/
public static String getFileExt(String fileName) {
int point = fileName.lastIndexOf('.');
int length = fileName.length();
if (point == -1 || point == length - 1) {
return "";
} else {
return fileName.substring(point + 1, length);
}
} /**
* 删除文件夹及其下面的子文件夹
*
* @param dir
* @throws IOException
*/
public static void deleteDir(File dir) throws IOException {
if (dir.isFile())
throw new IOException("IOException -> BadInputException: not a directory.");
File[] files = dir.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isFile()) {
file.delete();
} else {
deleteDir(file);
}
}
}
dir.delete();
} /**
* 复制文件
*
* @param src
* @param dst
* @throws Exception
*/
public static void copy(File src, File dst) throws Exception {
int BUFFER_SIZE = 4096;
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
throw e;
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
in = null;
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
out = null;
}
}
} }
JAVA FileUtils(文件读写以及操作工具类)的更多相关文章
- 沉淀再出发:java的文件读写
沉淀再出发:java的文件读写 一.前言 对于java的文件读写是我们必须使用的一项基本技能,因此了解其中的原理,字节流和字符流的本质有着重要的意义. 二.java中的I/O操作 2.1.文件读写的本 ...
- Java操作文件夹的工具类
Java操作文件夹的工具类 import java.io.File; public class DeleteDirectory { /** * 删除单个文件 * @param fileName 要删除 ...
- JAVA一个文件写多个类
JAVA一个文件写多个类,并且是同级类,需注意: 在一个.java文件中可以有多个同级类, 其修饰符只可以public/abstract/final/和无修饰符 public修饰的只能有一个,且必须 ...
- java FileUtils 文件工具类
package com.sicdt.library.core.utils; import java.io.BufferedInputStream; import java.io.File; impor ...
- Java的文件读写操作
file(内存)----输入流---->[程序]----输出流---->file(内存) 当我们读写文本文件的时候,采用Reader是非常方便的,比如FileReader,InputStr ...
- Java的文件读写操作 <转>
目录: file内存----输入流----程序----输出流----file内存 java中多种方式读文件 判断文件是否存在不存在创建文件 判断文件夹是否存在不存在创建文件夹 java 写文件的三种方 ...
- Android文件的流操作工具类
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import j ...
- [转]Java的文件读写操作
file(内存)----输入流---->[程序]----输出流---->file(内存) 当我们读写文本文件的时候,采用Reader是非常方便的,比如FileReader,InputStr ...
- java study文件读写
文件读写 如果在代码中写入大量的数据,会增加代码的冗余度,通过读取文件的方式,可以精简代码,便于数据的修改和代码的维护 IO流的分类:字节流和字符流 字符流 字符输出流:写文本文件的,抽象基类java ...
随机推荐
- 不是有效的win32应用程序
问题描述: 用vs2012编写的程序在xp下运行提示"不是有效的win32应用程序", 改成静态编译还是会提示上面的错误 解决办法: 原来常规里面的平台工具集的设置如上,更改为下面 ...
- python学习笔记:接口开发——PythonWEB框架之Flask
Flask是一个使用 Python 编写的轻量级 Web 应用框架,安装命令如下 pip install flask 一.服务端接口是怎么开发的? 1.启动一个服务 2.接收到客户端传过来的数据3.登 ...
- Linux(一)—— Linux环境搭建
Linux环境搭建 一.虚拟机安装 1.下载地址 https://my.vmware.com/web/vmware/info/slug/desktop_end_user_computing/vmwar ...
- shell编程:命令替换的运用
命令替换,有两种方式 方式一:`command` 方式二:$(command) user.sh 查找系统中所有的用户,并且输出 #!/bin/bash nginx=`netstat -tnlp | | ...
- MOS管知识大集
MOS管 增强型:就是UGS=0V时漏源极之间没有导电沟道,只有当UGS>开启电压(N沟道)或UGS<开启电压(P沟道)才可能出现导电沟道.耗尽型:就是UGS=0V时,漏源极之间存在导电沟 ...
- appium1.4+华为8.0执行自动化脚本,报启动session失败,原因是unicode_ime_apk\Uni codeIME-debug.apk在手机上已存在,再次安装失败,导致启动session失败,解决办法:换高版本的appium
最开始做Android自动化测试时,通过执行脚本发现报,已安装UnicodeIME-debug.apk,再次安装失败,当时觉得这个apk对我来说没用,就把D:\Program Files (x86)\ ...
- js中如何避免动态引入重复资源
创建存储数据的数组或者对象: 每次调用方法的时候,往里面添加资源对象,包括路径: 每次调用的时候遍历此路劲是否存在,如存在,就调用此资源对象的promise进行操作. 可避免资源未加载完成就执行的情况 ...
- bypass_safedog
1.SQL注入 手工bypass要点 先通过破坏关键字测试出拦截规则 之后进行针对性绕过 1.Mysql 1.1.联合注入 0x01 and绕过 直接 and 1=1 直接就会被拦截 在数值的前面加特 ...
- Python 调用自己编写的Class
假设自己写的 class 文件myPets.py放在当前目录的子目录/myClasses下,在myPets.py中定义了一个 class 叫Pet.现在要调用Pet这个 class : from my ...
- String的static方法
//String concat(String str) 拼接字符串 String concat_str0 = "abc"; String concat_str1 = "b ...