Skip to content

Commit

Permalink
重构FileUtils以便符合单元测试的要求
Browse files Browse the repository at this point in the history
  • Loading branch information
ysc committed Feb 11, 2014
1 parent 35f8b3a commit 999b104
Showing 1 changed file with 140 additions and 68 deletions.
208 changes: 140 additions & 68 deletions APDPlat_Core/src/main/java/org/apdplat/platform/util/FileUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,91 +28,118 @@
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Collections;
import java.util.List;
import org.apdplat.platform.log.APDPlatLoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Assert;

/**
*
* 文件操作类
* 可在生产环境(Web容器)下和开发环境下保持一致的使用方法
* 对于相对路径,可通过setBasePath方法指定前缀
* 开发环境下的相对路径其前缀为用户当前目录:System.getProperty("user.dir")
* 生产环境(Web容器)下的相对路径其前缀为应用的根目录:servletContextEvent.getServletContext().getRealPath("/")
* @author 杨尚川
*/
public class FileUtils {
private static final APDPlatLogger LOG = APDPlatLoggerFactory.getAPDPlatLogger(FileUtils.class);

/**
* 工具类,无实例对象,仅仅提供静态方法
*/
private FileUtils(){};

private static String basePath=System.getProperty("user.dir")+File.separator;

private static String basePath=System.getProperty("user.dir").replace("\\", "/");

/**
* 系统的默认目录为当前用户目录,可通过此函数重新设置
* @param basePath 相对路径前缀
*/
public static void setBasePath(String basePath) {
Assert.notNull(basePath);
FileUtils.basePath = basePath.replace("\\", "/");
}
/**
* 追加写入文件 -- 另起一行
* @param path 文件绝对路径
* @param text 要追加的文件内容
* @return 是否追加成功
*/
public static boolean appendTextInNewLine(String path,String text){
return appendText(path,text+System.getProperty("line.separator"));
}
/**
* 追加写入文件
* @param path 文件绝对路径
* @param text 要追加的文件内容
* @return
* @return 是否追加成功
*/
public static boolean appendText(String path,String text){
try{
File file=new File(path);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file,true))) {
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true), "utf-8"))) {
writer.write(text);
writer.close();
}
return true;
}catch(Exception e){
}catch(IOException e){
LOG.error("写文件出错",e);
}
return false;
}
/**
* 系统的默认目录为当前用户目录,可通过此函数重新设置
* @param basePath
*/
public static void setBasePath(String basePath) {
Assert.notNull(basePath);

if(!basePath.trim().endsWith(File.separator)){
basePath+=File.separator;
}
FileUtils.basePath = basePath;
}

/**
* 获取web根目录下面的资源的绝对路径
* @param path 相对应WEB根目录的路径
* 获取 web根目录或当前工作目录或指定目录 下面的资源的绝对路径
* / 返回 web根目录或当前工作目录或指定目录 的绝对路径
* /WEB-INF 返回 web根目录或当前工作目录或指定目录 下的WEB-INF 的绝对路径
* WEB-INF 返回 web根目录或当前工作目录或指定目录 下的WEB-INF 的绝对路径
*
* 特殊:对windows下的绝对路径不做转换
* c:/test/test.txt 返回 c:/test/test.txt
*
* @param path 相对于WEB根目录的路径
* @return 绝对路径
*/
public static String getAbsolutePath(String path){
Assert.notNull(path);
//在windows下,如果路径包含:,为绝对路径,则不进行转换
if(path.contains(":")){
return path;
return path.replace("\\", "/");
}
LOG.debug("转换路径:"+path);
path=path.replace("\\", "/").trim();
path=basePath+"/"+path;
while(path.contains("//")){
path=path.replace("//", "/");
}

LOG.debug("转换路径:"+path);
if(path!=null && path.trim().length()==1){
return basePath;
}
if(path.startsWith("/")){
path=path.substring(1);
}
path=basePath+path.replace("/", File.separator);
LOG.debug("返回路径:"+path);
return path;
}
/**
* 文件复制
* @param inFile 输入文件
* @param outFile 输出文件
*/
public static void copyFile(File inFile, File outFile){
try {
copyFile(new FileInputStream(inFile),outFile);
} catch (FileNotFoundException ex) {
LOG.error("文件不存在",ex);
}
}
/**
* 把输入流中的内容拷贝到一个文件
* @param in 输入流
* @param outFile 文件对象
*/
public static void copyFile(InputStream in, File outFile){
OutputStream out = null;
try {
Expand All @@ -139,7 +166,11 @@ public static void copyFile(InputStream in, File outFile){
}
}
}

/**
* 读取一个文件的所有字节
* @param file 文件对象
* @return 字节数组
*/
public static byte[] readAll(File file){
try {
return readAll(new FileInputStream(file));
Expand All @@ -148,7 +179,11 @@ public static byte[] readAll(File file){
}
return null;
}

/**
* 从输入流中读取所有字节
* @param in 输入流
* @return 字节数组
*/
public static byte[] readAll(InputStream in){
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
Expand All @@ -161,7 +196,11 @@ public static byte[] readAll(InputStream in){
}
return out.toByteArray();
}

/**
* 获取一个文件的输入流
* @param path 相对路径或绝对路径
* @return 文件输入流
*/
public static FileInputStream getInputStream(String path) {
try {
return new FileInputStream(getAbsolutePath(path));
Expand All @@ -170,6 +209,11 @@ public static FileInputStream getInputStream(String path) {
}
return null;
}
/**
* 判断一个文件是否存在
* @param path 相对路径或绝对路径
* @return 是否存在
*/
public static boolean existsFile(String path){
try{
File file=new File(getAbsolutePath(path));
Expand All @@ -181,7 +225,13 @@ public static boolean existsFile(String path){
}
return false;
}
public static File createAndWriteFile(String path,byte[] data){
/**
* 把字节内容写入新文件
* @param path 相对路径或绝对路径
* @param data 字节数组
* @return 新文件
*/
public static File createAndWriteFile(String path, byte[] data){
try{
File file=new File(getAbsolutePath(path));
if(!file.getParentFile().exists()){
Expand All @@ -197,7 +247,15 @@ public static File createAndWriteFile(String path,byte[] data){
}
return null;
}
public static File createAndWriteFile(String path,String text){
/**
* 把文本内容写入一个新文件
* 如果文件已经存在
* 则覆盖
* @param path 相对路径或绝对路径
* @param text 文本
* @return 文件
*/
public static File createAndWriteFile(String path, String text){
try{
File file=new File(getAbsolutePath(path));
if(!file.getParentFile().exists()){
Expand All @@ -213,57 +271,71 @@ public static File createAndWriteFile(String path,String text){
}
return null;
}

/**
* 删除文件
* @param path 相对路径或绝对路径
* @return 是否成功
*/
public static boolean removeFile(String path){
try{
File file=new File(getAbsolutePath(path));
if(file.exists()){
file.delete();
if(!file.delete()){
file.deleteOnExit();
}
}
return true;
}catch(Exception ex){
LOG.error("文件操作失败",ex);
}
return false;
}

public static Collection<String> getTextFileContent(String path) {
return getTextFileContent(getInputStream(path));
}

public static Collection<String> getTextFileContent(InputStream in) {
Collection<String> result=new LinkedHashSet<>();
BufferedReader reader = null;
/**
* 获取文本内容
* @param path 相对路径或绝对路径
* @return 行的列表
*/
public static List<String> getTextFileContent(String path) {
try {
reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
String line=reader.readLine();
while(line!=null){
//忽略空行和以#号开始的注释行
if(!"".equals(line.trim()) && !line.trim().startsWith("#")){
result.add(line);
}
line=reader.readLine();
}
} catch (UnsupportedEncodingException ex) {
LOG.error("不支持的编码",ex);
} catch (IOException ex) {
LOG.error("文件操作失败",ex);
} finally {
try {
reader.close();
} catch (IOException ex) {
LOG.error("文件操作失败",ex);
return getTextFileContent(new FileInputStream(getAbsolutePath(path)));
} catch (FileNotFoundException ex) {
LOG.error("文件不存在", ex);
}
//Null Object设计模式
return Collections.emptyList();
}
/**
* 获取输入流中的文本内容
* @param in 文本文件输入流
* @return 行的列表
*/
public static List<String> getTextFileContent(InputStream in) {
List<String> result = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"))) {
for (;;) {
String line = reader.readLine();
if (line == null)
break;
result.add(line);
}
} catch(Exception e){
LOG.error("读取文件失败",e);
}
return result;
}
/**
* 获取类路径下面的文本文件的内容
* @param path 类路径下面的文本文件
* @return 行的集合
*/
public static Collection<String> getClassPathTextFileContent(String path) {
try {
ClassPathResource cr = new ClassPathResource(path);
return getTextFileContent(cr.getInputStream());
} catch (IOException ex) {
LOG.error("文件操作失败",ex);
LOG.error("获取类路径资源失败",ex);
}
return null;
//Null Object设计模式
return Collections.emptyList();
}
}

0 comments on commit 999b104

Please sign in to comment.