Java操作文件的常用方法
1.包含: 解压文件、读取文件内容、删除文件、删除文件夹、将图片转换成二进制与还原。
2.FileUtils.java:
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import javax.imageio.ImageIO;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.junit.Test;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class FileUtils {
private static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
private static BASE64Decoder decoder = new sun.misc.BASE64Decoder();
public FileUtils() {
}
/**
* @param sourcefiles
* 源文件(服务器上的zip包存放地址)
* @param decompreDirectory
* 解压缩后文件存放的目录
* @throws IOException
* IO异常
*/
public static void unzip(String sourcefiles, String decompreDirectory) throws IOException {
ZipFile readfile = null;
try {
readfile = new ZipFile(sourcefiles);
Enumeration<?> takeentrie = readfile.getEntries();
ZipEntry zipEntry = null;
File credirectory = new File(decompreDirectory);
credirectory.mkdirs();
while (takeentrie.hasMoreElements()) {
zipEntry = (ZipEntry) takeentrie.nextElement();
String entryName = zipEntry.getName();
InputStream in = null;
FileOutputStream out = null;
try {
if (zipEntry.isDirectory()) {
String name = zipEntry.getName();
name = name.substring(0, name.length() - 1);
File createDirectory = new File(decompreDirectory + File.separator + name);
createDirectory.mkdirs();
} else {
int index = entryName.lastIndexOf("\\");
if (index != -1) {
File createDirectory = new File(
decompreDirectory + File.separator + entryName.substring(0, index));
createDirectory.mkdirs();
}
index = entryName.lastIndexOf("/");
if (index != -1) {
File createDirectory = new File(
decompreDirectory + File.separator + entryName.substring(0, index));
createDirectory.mkdirs();
}
File unpackfile = new File(decompreDirectory + File.separator + zipEntry.getName());
in = readfile.getInputStream(zipEntry);
out = new FileOutputStream(unpackfile);
int c;
byte[] by = new byte[1024];
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
out.flush();
}
} catch (IOException ex) {
ex.printStackTrace();
throw new IOException("解压失败:" + ex.toString());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
in = null;
out = null;
}
}
} catch (IOException ex) {
ex.printStackTrace();
throw new IOException("解压失败:" + ex.toString());
} finally {
if (readfile != null) {
try {
readfile.close();
} catch (IOException ex) {
ex.printStackTrace();
throw new IOException("解压失败:" + ex.toString());
}
}
}
}
/**
* @param filePath
* @param encode
* @return 读取文件内容
* @throws Exception
*/
public static String readFile(String filePath) {
return readFile(filePath, "utf-8");
}
/**
* @param filePath
* @param encode
* @param limit
* @return 读取文件内容
* @throws Exception
*/
public static String readFile(String filePath, String encode) {
String result = "";
File file = new File(filePath);
FileInputStream inputStream = null;
InputStreamReader inputReader = null;
try {
inputStream = new FileInputStream(file);
inputReader = new InputStreamReader(inputStream, encode);
BufferedReader br = new BufferedReader(inputReader);
String str = "";
while ((str = br.readLine()) != null) {
result += str + "\n"; // TODO \n
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
inputReader.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* @param filePath
* @return 删除文件
*/
public static boolean delFile(String filePath) {
boolean flag = false;
File file = new File(filePath);
if (file.isFile() && file.exists()) {
flag = file.delete();
}
return flag;
}
/**
* @param dir
* @return 删除文件夹
*/
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
// 递归删除目录中的子目录下
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// 目录此时为空,可以删除
return dir.delete();
}
/**
* 将图片转换成二进制
* @return
*/
public static String getImageBinary(File file) {
String fileName = file.getName();
// System.out.println(fileName + " " + fileName.substring(fileName.indexOf(".")+1, fileName.length()));
BufferedImage bi;
try {
bi = ImageIO.read(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, fileName.substring(fileName.indexOf(".")+1, fileName.length()), baos); // 经测试转换的图片是格式这里就什么格式,否则会失真
byte[] bytes = baos.toByteArray();
return encoder.encodeBuffer(bytes).trim();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* @param base64String
* @param savePath
* @param type
* 将二进制转换为图片
*/
public static void base64StringToImage(String base64String, String savePath) {
try {
byte[] bytes1 = decoder.decodeBuffer(base64String);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 = ImageIO.read(bais);
File w2 = new File(savePath);// File w2 = new File("e://QQ.jpg") 可以是jpg,png,gif格式
// TODO jpg
ImageIO.write(bi1, savePath.substring(savePath.indexOf(".")+1, savePath.length()), w2);// 不管输出什么格式图片,此处不需改动
} catch (IOException e) {
e.printStackTrace();
}
}
// 解压 zip
public static void main(String[] args) {
try {
unzip("D:/workplace/Producer/files/20190116.zip",
"D:/workplace/Producer/files/abc");
} catch (IOException e) {
e.printStackTrace();
}
}
// 读取内容
@Test
public void test01() {
System.out.println(
readFile("D:/workplace/Producer/files/20190116/1547449028337.txt"));
}
// 删除文件夹
@Test
public void test02() throws IOException {
unzip("D:/workplace/Producer/files/20190116.zip",
"D:/workplace/Producer/files/");
deleteDir(new File("D:/workplace/Producer/files/20190116"));
}
// 文件属性
@Test
public void test03() throws IOException {
File file = new File("D:/workplace/Producer/files/20190116.zip");
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
System.out.println(file.getPath());
System.out.println(file.getTotalSpace());
System.out.println(file.getFreeSpace());
System.out.println(file.getUsableSpace());
System.out.println(file.getParent());
}
// 图片处理
@Test
public void test04() {
String photo = getImageBinary(new File("D:/workplace/Producer/files/714b348d35e1e1ec3d5c769c8bbdb727__1.jpg"));
System.out.println(photo);
base64StringToImage(photo, "D:/workplace/Producer/files/20190114/a.jpg");
}
@Test
public void test05() {
String str = "abc\ndef\nghi";
String str_[] = str.split("\n");
System.out.println( str_.length + " " + str_[0] + "," + str_[1] + "," + str_[2] );
}
}
还没有评论,来说两句吧...