Java文件操作工具类
import com.foriseland.fjf.lang.DateUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* @version V1.0
* @ClassName FileUtil
* @Description
* @Author zhangyue
* @Date 2018/1/9 20:58
*/
public class FileUtil {
private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
/**
* 获得指定文件的byte数组
*/
public static byte[] getBytes(String filePath){
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
/**
* 根据byte数组,生成文件
*/
public static void getFile(byte[] bfile, String filePath,String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if(!dir.exists()){//判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath+"\\"+fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
/**
* byte[] 转InputStream
*/
public static final InputStream byte2Input(byte[] buf) {
return new ByteArrayInputStream(buf);
}
/**
* InputStream 转 byte[]
* @param inStream
* @return
* @throws IOException
*/
public static final byte[] input2byte(InputStream inStream)
throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
return in2b;
}
/**
* byte[] 转 InputStreamReader
*/
public static final InputStreamReader byte2Reader(byte[] buf) {
InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(buf));
return isr;
}
/**
* 删除文件
*
* @param pathname
* 文件名(包括路径)
*/
public static void deleteFile(String pathname){
File file = new File(pathname);
if(file.isFile() && file.exists()){
file.delete();
}
else{
logger.error("File["+ pathname +"] not exists!");
}
}
/**
* 删除文件树
*
* @param dirpath
* 文件夹路径
*/
public static void deleteFileTree(String dirpath) throws IOException {
File dir = new File(dirpath);
FileUtils.deleteDirectory(dir);
}
/**
* 获取文件扩展名
*
* @param fileName
* 文件名
* @return
*/
public static String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
/**
* 获取文件分隔符
*
* @return
*/
public static String getFileSeparator() {
return File.separator;
}
/**
* 获取相对路径
*
* @param params
* 按参数先后位置得到相对路径
* @return
*/
public static String getRelativePath(String... params){
if(null != params){
String path = "";
for(String str : params){
path = path + getFileSeparator() + str;
}
return path;
}
return null;
}
/**
* 把一个字符串写到指定文件中
* @param str 要写入文件中的字符串内容
* @param path 文件夹路径
* @param fileName 文件名称
*/
public static void writeStringToFile(String str,String path,String fileName) throws IOException {
File fileDir = new File(path);
if(!fileDir.exists()){
fileDir.mkdirs();
}
File file = new File(path+fileName);
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file,true);
fw.write(str);
fw.flush();
fw.close();
}
/**
* 在某个文件中追加内容
* @param fileName
* @param content
*/
public static void appendStringToFile(String fileName, String content) {
try {
//判断文件是否存在
File file = new File(fileName);
judeFileExists(file);
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
// 将写文件指针移到文件尾。
randomFile.seek(fileLength);
randomFile.write((content + "\r\n").getBytes());
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 判断文件是否存在,如果不存在则创建
public static void judeFileExists(File file) {
if (file.exists()) {
} else {
try {
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 判断文件夹是否存在,如果不存在则创建
public static void judeDirExists(File file) {
if (file.exists()) {
if (file.isDirectory()) {
System.out.println("dir exists");
} else {
System.out.println("the same name file exists, can not create dir");
}
} else {
System.out.println("dir not exists, create it ...");
file.mkdir();
}
}
}
Java文件操作工具类的更多相关文章
- JAVA文件操作工具类(读、增、删除、复制)
使用JAVA的JFinal框架 1.上传文件模型类UploadFile /** * Copyright (c) 2011-2017, James Zhan 詹波 (jfinal@126.com). * ...
- Java文件操作工具类(复制、删除、重命名、创建路径)
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import ...
- Code片段 : .properties属性文件操作工具类 & JSON工具类
摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “贵专” — 泥瓦匠 一.java.util.Properties API & 案例 j ...
- 文件操作工具类: 文件/目录的创建、删除、移动、复制、zip压缩与解压.
FileOperationUtils.java package com.xnl.utils; import java.io.BufferedInputStream; import java.io.Bu ...
- Android文件操作工具类(转)
Android文件操作工具类(转) 2014/4/3 18:13:35 孤独的旅行家 博客园 这个工具类包含Android应用开发最基本的几个文件操作方法,也是我第一次发博客与大家分享自己写的东 ...
- 小米开源文件管理器MiCodeFileExplorer-源码研究(4)-文件操作工具类FileOperationHelper
文件操作是非常通用的,注释都写在源代码中了,不多说~需要特别说明的是,任务的异步执行和IOperationProgressListener.拷贝和删除等操作,是比较费时的,采用了异步执行的方式~ An ...
- docker 部署vsftpd服务、验证及java ftp操作工具类
docker部署vsftpd服务 新建ftp文件存储目录/home/ftp cd /home mkdir ftp 创建一个组,用于存放ftp用户 groupadd ftpgroups 创建ftp用户, ...
- JAVA文件操作类和文件夹的操作代码示例
JAVA文件操作类和文件夹的操作代码实例,包括读取文本文件内容, 新建目录,多级目录创建,新建文件,有编码方式的文件创建, 删除文件,删除文件夹,删除指定文件夹下所有文件, 复制单个文件,复制整个文件 ...
- 【安卓】安卓res文件夹下的资源文件与R.java文件里面类的对应关系
对于drawable.layout.menu文件夹下的每一个文件都分别会在R.java文件里面生成drawable.layout.menu类的一个常量,类名就是文件夹的名字,常量的名字就是文件名字. ...
随机推荐
- 获取app应用的包名
1.获取哪个app包名,就打开哪个app 2.在dos窗口下输入: adb shell "dumpsys window | grep mCurrentFocus" 获取包名
- 我的Python升级打怪之路【二】:Python的基本数据类型及操作
基本数据类型 1.数字 int(整型) 在32位机器上,整数的位数是32位,取值范围是-2**31~2--31-1 在64位系统上,整数的位数是64位,取值范围是-2**63~2**63-1 clas ...
- JavaScript 函数用途
在JavaScript中,函数可以:被赋值给一个变量,被赋值为对象的属性.作为参数被传入别的函数.作为函数的结果被返回.用字面量来创建. 1. 赋值给一个变量 //声明一个函数,接受两个参数 func ...
- maven打包报错 ERROR: No goals have been specified for this build. You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id
打开pom.xml 在build标签中 增加 <defaultGoal>compile</defaultGoal> 如下: <build><defaultGo ...
- Freemarker list的使用
更新多条记录的操作,这里ids是一个数组 <sqltemplate id = "disableBuildLabourer"> <![CDATA[ UPDATE b ...
- 44个 Javascript 变态题解析
原题来自: http://javascript-puzzlers.herokuapp.com/ 读者可以先去做一下感受感受. 当初笔者的成绩是 21/44... 当初笔者做这套题的时候不仅怀疑智商, ...
- [转]glyphicons-halflings-regular字体 图标
本文转自:http://www.ijquery.cn/?p=377 一.介绍 采用这种字体,我们可以避免网站制作中采用好多图片,一方面解决了浏览器的兼容性问题.另一方面,这些字体都是矢量字体,我们只要 ...
- window.open以post方式提交(转)
function openWindowWithPost(url,name,keys,values) { var newWindow = window.open(url, name); if (!new ...
- golang学习之文件上传
首先是上传页面upload.html: <!doctype html> <html> <head> <meta charset="utf-8&quo ...
- C#基础:传入URL,获得Http Post
#region 传入url,获得Http Post public string HttpGet(string url) { string result = string.Empty; try { va ...