⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 reader.java

📁 Helper class used for reading the content of a file.
💻 JAVA
字号:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.apache.log4j.Logger;

/**
 * Helper class used for reading the content of a file.
 * 
 * @author Tolnai Andrei Ciprian
 * 
 */
public class Reader {

	/**
	 * The logger.
	 */
	private static final Logger log = Logger.getLogger(Reader.class);

	/**
	 * Default constructor is hidden.
	 */
	private Reader() {
	}

	/**
	 * Fetch the entire contents of a text file, and return it in a String. This
	 * style of implementation does not throw Exceptions to the caller.
	 * 
	 * @param filePath
	 *            The absolute path to the file to read from.
	 * @return
	 */
	public static String read(String filePath) {
		log.debug("Reading from file: " + filePath);
		return read_(filePath, true);
	}

	/**
	 * Fetch the entire contents of a text file ignoring new line, and return it
	 * in a String. This style of implementation does not throw Exceptions to
	 * the caller.
	 * 
	 * @param filePath
	 *            The absolute path to the file to read from.
	 * @return
	 */
	public static String readWithoutNewLine(String filePath) {
		log.debug("Reading without new line from file: " + filePath);
		return read_(filePath, false);
	}

	/**
	 * The actual method that does the reading.
	 * 
	 * @param filePath
	 *            The absolute path to the file to read from.
	 * @param withNewLine
	 *            Content will be read with or without new lines.
	 * @return
	 */
	private static String read_(String filePath, boolean withNewLine) {
		File file = new File(filePath);
		StringBuilder contents = new StringBuilder();

		try {
			BufferedReader input = new BufferedReader(new FileReader(file));
			try {
				String line = null;
				while ((line = input.readLine()) != null) {
					contents.append(line);
					if (withNewLine) {
						contents.append(System.getProperty("line.separator"));
					}
				}
			} finally {
				input.close();
			}
		} catch (IOException ex) {
			log.error("IOException", ex);
		}

		return contents.toString();
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -