[1] String fileReaderStringHandle(String fileName)
將文件(由fileName指定)讀入到一個字符串;
[2] byte[] fileReaderByteHandle(String fileName)
將文件(由fileName指定)讀入到一個字節數組;
[3] void fileWriterHandle(String fileName, String text)
將字符串(由text指定)寫出到一個文件(由fileName指定)。
IOUtil.java
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class IOUtil {
/**
* 將文件讀入到一個String,利用FileReader+BufferedReader(提供readLine方法)
*
* @param fileName
* @return String
*/
public static String fileReaderStringHandle(String fileName) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader(new File(
fileName).getAbsoluteFile()));
try {
String s;
while ((s = in.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} finally {
in.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}
/**
* 使用FileInputStream+BufferedInputStream以byte的方式處理文件
*
* @param fileName
* @return byte[]
*/
public static byte[] fileReaderByteHandle(String fileName) {
byte[] data = null;
try {
BufferedInputStream bf = new BufferedInputStream(
new FileInputStream(fileName));
try {
data = new byte[bf.available()];
bf.read(data);
} finally {
bf.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return data == null ? new byte[] {} : data;
}
/**
* 將指定的text寫入到文件名為fileName的文件中
*
* @param fileName
* @param text
*/
public static void fileWriterHandle(String fileName, String text) {
try {
PrintWriter out = new PrintWriter(new File(fileName)
.getAbsoluteFile());
try {
out.print(text);
} finally {
out.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws IOException {
System.out.print(fileReaderStringHandle("src/IOUtil.java"));
for (byte b : fileReaderByteHandle("src/IOUtil.java"))
System.out.print(b);
fileWriterHandle("zj.txt",
fileReaderStringHandle("src/IOUtil.java"));
}
}
本文出自 “子 孑” 博客,請務必保留此出處http://zhangjunhd.blog.51cto.com/113473/74647