spring boot 获取 src 目录下的 文档结构,以及读写 页面文件

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.DirectoryStream.Filter;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;


@Service
public class FileUtil {
	
	@Value("${cms.defaultEncode}")
	public String defaultEncode;
	
	@Value("${cms.maxReadFileSize}")
	public Long maxReadFileSize;
	
	@Value("${spring.profiles.active}")
	private String profilesActive;
	
	Logger logger = LoggerFactory.getLogger(FileUtil.class);
	
	static String classPathRoot;

	public StringBuilder getFileContentToString(String filePath){
		StringBuilder fileContent = new StringBuilder();
		Path filepath = Paths.get(filePath);
		File file = filepath.toFile();
		RandomAccessFile randomAccessFile = null;
		try {
			if(file.exists()){
				randomAccessFile = new RandomAccessFile(file, "r");
				//从头开始读
				randomAccessFile.seek(0);
				String tempString = null;
				while(null != (tempString = randomAccessFile.readLine())){
					fileContent.append(new String(tempString.getBytes(),defaultEncode)).append('\u005Cr');
				}
			}
		} catch (IOException ee) {
			logger.error(ee.getMessage(),ee);
		}
		finally {
			if(null != randomAccessFile){
				try {
					randomAccessFile.close();
				} catch (IOException e) {
					logger.error(e.getMessage(),e);
				}
			}
		}
		
		return fileContent;
	}
	
	public boolean createFileContentToLocalFile(String filePath,String content){
		Path filepath = Paths.get(filePath);
		File file = filepath.toFile();

		FileOutputStream fileOutputStream = null;
		if(!filepath.getParent().toFile().exists()){
			filepath.getParent().toFile().mkdir();
		}
		try {
			Files.createFile(filepath);
			
			//覆盖
			fileOutputStream = new FileOutputStream(file,false);
			fileOutputStream.write(content.getBytes(defaultEncode));
			
		} catch (Exception ee) {
			logger.error(ee.getMessage(),ee);
			return false;
		}
		finally{
			if(null != fileOutputStream){
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					logger.error(e.getMessage(),e);
					return false;
				}
			}
		}
		
		return true;
	}
	
	public boolean saveFileContentToLocalFile(String filePath,String content){
		Path filepath = Paths.get(filePath);
		File file = filepath.toFile();
		
		String templateFileName = "SYS_TEMP_" + file.getName();
		Path tempFilepath = Paths.get(file.getParentFile().getPath()+File.separator+templateFileName);
		File fileTemp = tempFilepath.toFile();
		
		FileOutputStream fileOutputStream = null;
		//FileOutputStream tempFileOutputStream = null;
		//PrintStream printStream = null;  
		try {
			//fileTemp.createNewFile();
			//追加
			//tempFileOutputStream = new FileOutputStream(fileTemp,true);
			//覆盖
			//tempFileOutputStream = new FileOutputStream(fileTemp,false);
			//tempFileOutputStream.write(content.getBytes(defaultEncode));
//			printStream = new PrintStream(tempFileOutputStream); 
//			printStream.print(content);
			

			//先保存一下防止异常
			Files.copy(filepath, tempFilepath);
			
			//覆盖
			if(null != file ){
				file.delete();
			}
			
			fileOutputStream = new FileOutputStream(file,false);
			fileOutputStream.write(content.getBytes(defaultEncode));
			
		} catch (Exception ee) {
			logger.error(ee.getMessage(),ee);
			return false;
		}
		finally{
//			if(null != printStream){
//				printStream.close();
//			}
			if(null != fileOutputStream){
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					logger.error(e.getMessage(),e);
					return false;
				}
			}
//			if(null != tempFileOutputStream){
//				try {
//					tempFileOutputStream.close();
//				} catch (IOException e) {
//					logger.error(e.getMessage(),e);
//					return false;
//				}
//			}
			
			if(null != fileTemp){
				fileTemp.delete();
			}
			
		}
		
		return true;
	}

	public List<File> getFileList(String path) {
		List<File> result = new ArrayList<File>();
		
		Path readPath = Paths.get(path);
		File fileFromPath = readPath.toFile();
		
		if(fileFromPath.isDirectory()){
 
			File[] fileList = fileFromPath.listFiles(new FileFilter() {
				
//				//只取文件
//				@Override
//				public boolean accept(File pathname) {
//					if(null != pathname && pathname.isFile() ){
//						return true;
//					}
//					else{
//						return false;
//					}
//				}
				
				//所有文件 文件夹都取
				@Override
				public boolean accept(File pathname) {
					if(null != pathname ){
						return true;
					}
					else{
						return false;
					}
				}
			});
			
			result = Arrays.asList(fileList);
		}
		else{
			
		}
		
		
		return result;
	}
	
	public String getFileContentToString(File file) {
		ByteArrayOutputStream baos = null;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			for (int len = 0; (len = fis.read(buffer)) > 0;) {
				baos.write(buffer, 0, len);
			}
			return new String(baos.toByteArray(),defaultEncode);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		} finally {
			try {
				if(null != baos){
					baos.close();
				}
				if(null != fis){
					fis.close();
				}
			} catch (Exception e2) {
				logger.error(e2.getMessage(),e2);
			}
		}
		return null;
	}

	public void writeString(File file, String string) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file, false);
			fos.write(string.getBytes(defaultEncode));
		} catch (Exception e) {
		} finally {
			try {
				if(null != fos){
					fos.close();
				}
			} catch (Exception e2) {
				logger.error(e2.getMessage(),e2);
			}

		}
	}

	public void deleteFile(String filePath) {
		Path filepath = Paths.get(filePath);
		File file = filepath.toFile();
		file.delete();
	}
	
	public String getClassPathRoot(){
		
		if(null == classPathRoot || "".equals(classPathRoot)){
			try {
				classPathRoot = ResourceUtils.getURL("classpath:").toURI().getRawPath();
		    	if("dev".equals(profilesActive) && classPathRoot.startsWith("/")){
		    		classPathRoot = classPathRoot.substring("/".length());
		    	}
			} catch (FileNotFoundException | URISyntaxException e) {
				logger.error("获取工程根路径出错"+e.getMessage(),e);
			}
		}
		
		return classPathRoot;
	}
}

猜你喜欢

转载自blog.csdn.net/wuyezhiyu/article/details/80193262
今日推荐