Java 文件讀寫的實用工具
package org.rui.io.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;
/**
* 文件讀寫的實用工具
* @author lenovo
*
*/
public class TextFile extends ArrayList<String>{
//讀取一個文件,並返回字符串
public static String read(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 (Exception e) {
throw new RuntimeException(e);
}
return sb.toString();
}
// write a single
public static void write(String fileName,String text)
{
try {
PrintWriter out=new PrintWriter(
new File(fileName).getAbsoluteFile()
);
try {
out.print(text);
}finally
{
out.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// read a file
public TextFile(String fileName,String splitter)
{
//放入集合,
super(Arrays.asList(read(fileName).split(splitter)));
if(get(0).equals("")) remove(0);
}
public TextFile(String fileName)
{
//重載當前構造器
this(fileName,"\n");
}
public void write(String fileName)
{
try {
PrintWriter out=new PrintWriter(
new File(fileName).getAbsoluteFile()
);
try {
for(String item:this){
//System.out.println(item);
out.println(item);
}
} finally
{
out.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/////simple test
public static void main(String[] args) {
//路徑根據自已的改
String path="D:\\Users\\liangrui\\workspace\\thinking\\src\\org\\rui\\io\\util/";
String fileText =read(path+"TextFile.java");//讀取當前java文本
//寫入文件
write(path+"newText.txt",fileText);
//對象 寫
TextFile tf=new TextFile(path+"newText.txt");//再次讀取寫入的新文本
tf.write(path+"newText2.txt");//再次寫入
//讀取文本並放入TreeSet集合中
TreeSet<String> words=new TreeSet<String>(
new TextFile(path+"TextFile.java","\\W+")//\W詞字符
);
//headSet 返回此 set 的部分視圖,其元素嚴格小於 toElement。
System.out.println(words.headSet("a"));
}
}
/**
* output:
[0, ArrayList, Arrays, BufferedReader, D, Exception, File,
FileReader, PrintWriter, RuntimeException, String, StringBuilder,
System, TextFile, TreeSet, Users, W]
*/
----------------------分割線----------------------
package org.rui.io.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* 讀取二進制文件
* @author lenovo
*
*/
public class BinaryFile {
public static byte[] read(File bFile) throws IOException
{
BufferedInputStream bis=new BufferedInputStream(
new FileInputStream(bFile)
);
try {
//產生恰當數組尺寸
byte[] data=new byte[bis.available()];
bis.read(data);
return data;
} finally
{
bis.close();
}
}
public static byte[] read(String bF) throws IOException
{
//重載
return read(new File(bF).getAbsoluteFile());// getAbsoluteFile 返回此抽象路徑名的絕對路徑名形式。
}
}