Java:IO操作工具类
时间:2011-02-17 zhangjunhd
[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 |