Java:IO操作工具类[Java编程]
本文“Java:IO操作工具类[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
[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
以上是“Java:IO操作工具类[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |