文件讀寫工具類

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
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.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class FileOperation {
	
	private static Logger logger = LogManager.getLogger(FileOperation.class.getName());

	/***
	 * 根據參數路徑遍歷磁盤 獲取文件列表
	 * 
	 * @param initial
	 * @return fileListG 文件列表
	 */
	private LinkedList<File> fileListG = new LinkedList<File>();

	public List<File> getFileList(String initialPath) {
		if (initialPath == null)
			throw new NullPointerException();
		File file = new File(initialPath);
		if (file.isDirectory()) {
			File[] fileList = file.listFiles();
			if (fileList != null)
				for (File childF : fileList) {
					if (childF.isDirectory()) {
						getFileList(childF.getAbsolutePath());
					} else {
						fileListG.add(childF);
					}
				}
		}
		return fileListG;
	}

	public void serialization(String pathname, Object obj) {
		try {
			File file = new File(pathname);
			OutputStream fos = new FileOutputStream(file);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(obj);
			oos.flush();
			oos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Object deserialization(String pathname) {
		Object objChile = null;
		FileInputStream fis;
		try {
			fis = new FileInputStream(new File(pathname));
			ObjectInputStream ois = new ObjectInputStream(fis);
			objChile = ois.readObject();
			ois.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return objChile;
	}

	public void writeFile(String pathName, String text) {
		try {
			FileWriter fw = new FileWriter(new File(pathName));
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(text);
			bw.flush();
			bw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 寫入文件
	 * @param file
	 * @param text
	 */
	public void writeFile(File file, String text) {
		try {
			FileWriter fw = new FileWriter(file);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(text);
			bw.flush();
			bw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 追加寫入文件
	 * @param file
	 * @param text
	 */
	public void appendFile(File file, String text) {
		BufferedWriter out = null;
		try{
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
			out.write(text);
		}catch(Exception e){
			logger.info("文件加載錯誤,未找到文件" + file.getName());
		}finally{
			try{
				if(null != out){
					out.flush();
					out.close();
				}
			}catch(Exception e){
				
			}
		}
	}

	public void serialization(File file, Object obj) {
		try {
			OutputStream fos = new FileOutputStream(file);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(obj);
			oos.flush();
			oos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Object deserialization(File file) {
		Object objChile = null;
		FileInputStream fis;
		try {
			fis = new FileInputStream(file);
			ObjectInputStream ois = new ObjectInputStream(fis);
			objChile = ois.readObject();
			ois.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return objChile;
	}

	public Object ReadSerializableDateXML(String pathname) {
		File fin = new File(pathname);
		FileInputStream fis;
		Object obj = null;
		try {
			fis = new FileInputStream(fin);
			XMLDecoder decoder = new XMLDecoder(fis);
			obj = decoder.readObject();
			fis.close();
			decoder.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return obj;
	}

	public void WriteSerializableDateXML(String pathname, Object obj) {
		try {
			File fo = new File(pathname);
			FileOutputStream fos = new FileOutputStream(fo);
			XMLEncoder encoder = new XMLEncoder(fos);
			encoder.writeObject(obj);
			encoder.flush();
			encoder.close();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/****
	 * 獲取classPath
	 */
	public String getClassPath() {
		URL url = FileOperation.class.getProtectionDomain().getCodeSource().getLocation(); // Gets the path
		String jarPath = null;
		try {
			jarPath = URLDecoder.decode(url.getFile(), "UTF-8"); // Should fix
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String parentPath = new File(jarPath).getParentFile().getPath(); // Path
		parentPath = parentPath + File.separator;
		return parentPath;
	}

	/***
	 * 根據要查找的文件名稱在path下查找配置文件路徑
	 */
	public String queryFilePath(String path, String propertyFileName) {
		for (File file : new FileOperation().getFileList(path)) {
			if (file.getName().equals(propertyFileName))
				return file.getAbsolutePath();
		}
		return null;
	}

	public String readFile(String path, String charset) {
		if (path == null || charset == null)
			throw new NullPointerException();
		File file = new File(path);
		StringBuilder sb = new StringBuilder();
		BufferedReader br = null;
		InputStreamReader isr = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			isr = new InputStreamReader(fis, charset);
			br = new BufferedReader(isr);
			while (br.ready())
				sb.append(br.readLine());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
				isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	/**
	 * 讀取文件
	 * @param path
	 * @param charset
	 * @return
	 */
	public List<String> readFileLines(String path, String charset) {
		if (path == null || charset == null)
			throw new NullPointerException();
		List<String> lines = new ArrayList<String>();
		File file = new File(path);
		BufferedReader br = null;
		InputStreamReader isr = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			isr = new InputStreamReader(fis, charset);
			br = new BufferedReader(isr);
			while (br.ready())
				lines.add(br.readLine());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
				isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return lines;
	}
	/**
	 * 讀取文件流
	 * @param is
	 * @param charset
	 * @return
	 */
	public List<String> readFileLines(InputStream is, String charset) {
		if (charset == null)
			throw new NullPointerException();
		List<String> lines = new ArrayList<String>();
		BufferedReader br = null;
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(is, charset);
			br = new BufferedReader(isr);
			while (br.ready())
				lines.add(br.readLine());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(null != br){
					br.close();
				}
				if(null != isr){
					isr.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return lines;
	}
	
	/**
	 * 讀取文件流
	 * @param is
	 * @param charset
	 * @return
	 */
	public HashSet<String> readFileLinesToSet(InputStream is, String charset) {
		if (charset == null)
			throw new NullPointerException();
		HashSet<String> lines = new HashSet<String>();
		BufferedReader br = null;
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(is, charset);
			br = new BufferedReader(isr);
			while (br.ready())
				lines.add(br.readLine());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
				isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return lines;
	}

	public String readFile(File file, String charset) {
		StringBuilder sb = new StringBuilder();
		BufferedReader br = null;
		InputStreamReader isr = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			isr = new InputStreamReader(fis, charset);
			br = new BufferedReader(isr);
			while (br.ready())
				sb.append(br.readLine());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
				isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	/**
	 * 根據文件名稱查找文件流
	 * @param fileName
	 * @return
	 */
	public InputStream getInputStream(String fileName){
		InputStream is = null;
		try {
			//讀取class路徑下面的文件
			is = FileOperation.class.getClassLoader().getResourceAsStream(fileName);
		} catch (Exception e) {
			is = getInputStreamFromConf(fileName);
		}
		if(null == is){
			is = getInputStreamFromConf(fileName);
		}
		return is;
	}
	
	/**
	 * 從conf中獲取配置文件流
	 * @param fileName
	 * @return
	 */
	public InputStream getInputStreamFromConf(String fileName){
		InputStream is = null;
		//讀取conf路徑下面的文件
		File conf = new File(new File(new FileOperation().getClassPath()).getParentFile(), "conf");
		File file = new File(conf, fileName);
		try {
			is = new FileInputStream(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return is;
	}
	/**
	 * 獲取資源路徑
	 * @return
	 */
	public String getResourcePath(){
		String path = "";
		//讀取conf路徑下面的文件
		try{
			File conf = new File(new File(new FileOperation().getClassPath()).getParentFile(), "conf");
			if(conf.isDirectory()){
				path = conf.getAbsolutePath();
			}else{
				path = FileOperation.class.getClassLoader().getResource("").getFile().toString();
			}
		}catch(Exception e){
			logger.info("資源路徑未找到!");
		}
		
		return path;
	}
	public static void main(String[] args) {
		FileOperation operation = new FileOperation();
		System.out.println(operation.getResourcePath());
		/*System.out.println(operation.getClassPath());
		InputStream is = operation.getInputStream("xinjiang/keywords.txt");
		List<String> keywords = new FileOperation().readFileLines(is, "utf-8"); // 讀取文本
		for(String keyword:keywords){
			System.out.println(keyword);
		}*/
	}
}

直接拿去用就行了java

相關文章
相關標籤/搜索