package com.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.StringReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileUtil {
private static Logger log = LoggerFactory.getLogger(FileUtil.class);
public static void createDir(String dir, boolean ignoreIfExitst)
throws IOException {
File file = new File(dir);
if (ignoreIfExitst && file.exists()) {
return;
}
if (file.mkdir() == false) {
throw new IOException("Cannot create the directory = " + dir);
}
}
public static void createDirs(String dir, boolean ignoreIfExitst)
throws IOException {
File file = new File(dir);
if (ignoreIfExitst && file.exists()) {
return;
}
if (file.mkdirs() == false) {
throw new IOException("Cannot create directories = " + dir);
}
}
public static void deleteFile(String filename) throws IOException {
File file = new File(filename);
log.trace("Delete file = " + filename);
if (file.isDirectory()) {
throw new IOException(
"IOException -> BadInputException: not a file.");
}
if (file.exists() == false) {
throw new IOException(
"IOException -> BadInputException: file is not exist.");
}
if (file.delete() == false) {
throw new IOException("Cannot delete file. filename = " + filename);
}
}
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();
}
public static String getPathSeparator() {
return java.io.File.pathSeparator;
}
public static String getFileSeparator() {
return java.io.File.separator;
}
public static long getDirLength(File dir) throws IOException {
if (dir.isFile())
throw new IOException("BadInputException: not a directory.");
long size = 0;
File[] files = dir.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
long length = 0;
if (file.isFile()) {
length = file.length();
} else {
length = getDirLength(file);
}
size += length;
}
}
return size;
}
public static void emptyFile(String srcFilename) throws IOException {
File srcFile = new File(srcFilename);
if (!srcFile.exists()) {
throw new FileNotFoundException("Cannot find the file: "
+ srcFile.getAbsolutePath());
}
if (!srcFile.canWrite()) {
throw new IOException("Cannot write the file: "
+ srcFile.getAbsolutePath());
}
FileOutputStream outputStream = new FileOutputStream(srcFilename);
outputStream.close();
}
public static void writeFile(String content, String fileName,
String destEncoding) throws FileNotFoundException, IOException {
File file = null;
try {
file = new File(fileName);
if (!file.exists()) {
if (file.createNewFile() == false) {
throw new IOException("create file '" + fileName
+ "' failure.");
}
}
if (file.isFile() == false) {
throw new IOException("'" + fileName + "' is not a file.");
}
if (file.canWrite() == false) {
throw new IOException("'" + fileName + "' is a read-only file.");
}
} finally {
}
BufferedWriter out = null;
try {
FileOutputStream fos = new FileOutputStream(fileName);
out = new BufferedWriter(new OutputStreamWriter(fos, destEncoding));
out.write(content);
out.flush();
} catch (FileNotFoundException fe) {
log.error("Error", fe);
throw fe;
} catch (IOException e) {
log.error("Error", e);
throw e;
} finally {
try {
if (out != null)
out.close();
} catch (IOException ex) {
}
}
}
public static void writeFile(byte[] b, String fileName)
throws FileNotFoundException, IOException {
File file = null;
try {
file = new File(fileName);
if (!file.exists()) {
if (file.createNewFile() == false) {
throw new IOException("create file '" + fileName
+ "' failure.");
}
}
if (file.isFile() == false) {
throw new IOException("'" + fileName + "' is not a file.");
}
if (file.canWrite() == false) {
throw new IOException("'" + fileName + "' is a read-only file.");
}
} finally {
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fileName);
fos.write(b, 0, b.length);
fos.flush();
} catch (FileNotFoundException fe) {
log.error("Error", fe);
throw fe;
} catch (IOException e) {
log.error("Error", e);
throw e;
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException ex) {
}
}
}
public static String readFile(String fileName, String srcEncoding)
throws FileNotFoundException, IOException {
File file = null;
try {
file = new File(fileName);
if (file.isFile() == false) {
throw new IOException("'" + fileName + "' is not a file.");
}
} finally {
}
BufferedReader reader = null;
try {
StringBuffer result = new StringBuffer(1024);
FileInputStream fis = new FileInputStream(fileName);
reader = new BufferedReader(new InputStreamReader(fis, srcEncoding));
char[] block = new char[512];
while (true) {
int readLength = reader.read(block);
if (readLength == -1)
break;
result.append(block, 0, readLength);
}
return result.toString();
} catch (FileNotFoundException fe) {
log.error("Error", fe);
throw fe;
} catch (IOException e) {
log.error("Error", e);
throw e;
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException ex) {
}
}
}
public static String[] getLastLines(File file, int linesToReturn)
throws IOException, FileNotFoundException {
final int AVERAGE_CHARS_PER_LINE = 250;
final int BYTES_PER_CHAR = 2;
RandomAccessFile randomAccessFile = null;
StringBuffer buffer = new StringBuffer(linesToReturn
* AVERAGE_CHARS_PER_LINE);
int lineTotal = 0;
try {
randomAccessFile = new RandomAccessFile(file, "r");
long byteTotal = randomAccessFile.length();
long byteEstimateToRead = linesToReturn * AVERAGE_CHARS_PER_LINE
* BYTES_PER_CHAR;
long offset = byteTotal - byteEstimateToRead;
if (offset < 0) {
offset = 0;
}
randomAccessFile.seek(offset);
String line = null;
String lineUTF8 = null;
while ((line = randomAccessFile.readLine()) != null) {
lineUTF8 = new String(line.getBytes("ISO8859_1"), "UTF-8");
lineTotal++;
buffer.append(lineUTF8).append("/n");
}
} finally {
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException ex) {
}
}
}
String[] resultLines = new String[linesToReturn];
BufferedReader in = null;
try {
in = new BufferedReader(new StringReader(buffer.toString()));
int start = lineTotal - linesToReturn;
if (start < 0)
start = 0;
for (int i = 0; i < start; i++) {
in.readLine();
}
int i = 0;
String line = null;
while ((line = in.readLine()) != null) {
resultLines[i] = line;
i++;
}
} catch (IOException ie) {
log.error("Error" + ie);
throw ie;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
}
}
}
return resultLines;
}
public static void copyFile(String srcFilename, String destFilename,
boolean overwrite) throws IOException {
File srcFile = new File(srcFilename);
if (!srcFile.exists()) {
throw new FileNotFoundException("Cannot find the source file: "
+ srcFile.getAbsolutePath());
}
if (!srcFile.canRead()) {
throw new IOException("Cannot read the source file: "
+ srcFile.getAbsolutePath());
}
File destFile = new File(destFilename);
if (overwrite == false) {
if (destFile.exists())
return;
} else {
if (destFile.exists()) {
if (!destFile.canWrite()) {
throw new IOException("Cannot write the destination file: "
+ destFile.getAbsolutePath());
}
} else {
if (!destFile.createNewFile()) {
throw new IOException("Cannot write the destination file: "
+ destFile.getAbsolutePath());
}
}
}
BufferedInputStream inputStream = null;
BufferedOutputStream outputStream = null;
byte[] block = new byte[1024];
try {
inputStream = new BufferedInputStream(new FileInputStream(srcFile));
outputStream = new BufferedOutputStream(new FileOutputStream(
destFile));
while (true) {
int readLength = inputStream.read(block);
if (readLength == -1)
break;
outputStream.write(block, 0, readLength);
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ex) {
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) {
}
}
}
}
public static void copyFile(File srcFile, File destFile, boolean overwrite)
throws IOException {
if (!srcFile.exists()) {
throw new FileNotFoundException("Cannot find the source file: "
+ srcFile.getAbsolutePath());
}
if (!srcFile.canRead()) {
throw new IOException("Cannot read the source file: "
+ srcFile.getAbsolutePath());
}
if (overwrite == false) {
if (destFile.exists())
return;
} else {
if (destFile.exists()) {
if (!destFile.canWrite()) {
throw new IOException("Cannot write the destination file: "
+ destFile.getAbsolutePath());
}
} else {
if (!destFile.createNewFile()) {
throw new IOException("Cannot write the destination file: "
+ destFile.getAbsolutePath());
}
}
}
BufferedInputStream inputStream = null;
BufferedOutputStream outputStream = null;
byte[] block = new byte[1024];
try {
inputStream = new BufferedInputStream(new FileInputStream(srcFile));
outputStream = new BufferedOutputStream(new FileOutputStream(
destFile));
while (true) {
int readLength = inputStream.read(block);
if (readLength == -1)
break;
outputStream.write(block, 0, readLength);
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ex) {
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) {
}
}
}
}
public static void copyFiles(String srcDirName, String destDirName,
boolean overwrite) throws IOException {
File srcDir = new File(srcDirName);
if (!srcDir.exists()) {
throw new FileNotFoundException(
"Cannot find the source directory: "
+ srcDir.getAbsolutePath());
}
File destDir = new File(destDirName);
if (overwrite == false) {
if (destDir.exists()) {
} else {
if (destDir.mkdirs() == false) {
throw new IOException(
"Cannot create the destination directories = "
+ destDir);
}
}
} else {
if (destDir.exists()) {
} else {
if (destDir.mkdirs() == false) {
throw new IOException(
"Cannot create the destination directories = "
+ destDir);
}
}
}
File[] srcFiles = srcDir.listFiles();
if (srcFiles == null || srcFiles.length < 1) {
return;
}
int SRCLEN = srcFiles.length;
for (int i = 0; i < SRCLEN; i++) {
File destFile = new File(destDirName + File.separator
+ srcFiles[i].getName());
if (srcFiles[i].isFile()) {
copyFile(srcFiles[i], destFile, overwrite);
} else {
copyFiles(srcFiles[i].getAbsolutePath(), destDirName
+ File.separator + srcFiles[i].getName(), overwrite);
}
}
}
public static void zipFile(String srcFilename, String destFilename,
boolean overwrite) throws IOException {
File srcFile = new File(srcFilename);
if (!srcFile.exists()) {
throw new FileNotFoundException("Cannot find the source file: "
+ srcFile.getAbsolutePath());
}
if (!srcFile.canRead()) {
throw new IOException("Cannot read the source file: "
+ srcFile.getAbsolutePath());
}
if (destFilename == null || destFilename.trim().equals("")) {
destFilename = srcFilename + ".zip";
} else {
destFilename += ".zip";
}
File destFile = new File(destFilename);
if (overwrite == false) {
if (destFile.exists())
return;
} else {
if (destFile.exists()) {
if (!destFile.canWrite()) {
throw new IOException("Cannot write the destination file: "
+ destFile.getAbsolutePath());
}
} else {
if (!destFile.createNewFile()) {
throw new IOException("Cannot write the destination file: "
+ destFile.getAbsolutePath());
}
}
}
BufferedInputStream inputStream = null;
BufferedOutputStream outputStream = null;
ZipOutputStream zipOutputStream = null;
byte[] block = new byte[1024];
try {
inputStream = new BufferedInputStream(new FileInputStream(srcFile));
outputStream = new BufferedOutputStream(new FileOutputStream(
destFile));
zipOutputStream = new ZipOutputStream(outputStream);
zipOutputStream.setComment("通过java程序压缩的");
ZipEntry zipEntry = new ZipEntry(srcFile.getName());
zipEntry.setComment(" zipEntry通过java程序压缩的");
zipOutputStream.putNextEntry(zipEntry);
while (true) {
int readLength = inputStream.read(block);
if (readLength == -1)
break;
zipOutputStream.write(block, 0, readLength);
}
zipOutputStream.flush();
zipOutputStream.finish();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ex) {
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) {
}
}
if (zipOutputStream != null) {
try {
zipOutputStream.close();
} catch (IOException ex) {
}
}
}
}
public static void main(String[] args) throws IOException {
FileUtil.createDirs("d:/logs/aaaaaaaa/spring.log", false);
FileUtil.zipFile("d:/logs/复件 work.log", null, true);
System.out.println(getFileSeparator());
String[] temp = FileUtil.getLastLines(new File("d:/logs/work.log"), 5);
for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i]);
}
}
}