最近想学习java IO,看了thinking in java,总结下自己的学习所得:
还有一部分文件说明在 java IO的一些理解 (0),文件太多,放不下
package star20110524;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
public class BasicFileOutput {
static String file = "D:\\LEARN\\A\\B05\\star20110524\\BasicFileOutput.out";
public static void main(String[] args) throws IOException {
StringReader stringReader = new StringReader(BufferedInputFile.read("D:\\LEARN\\A\\B05\\star20110524\\BasicFileOutput.java"));
BufferedReader bufferedReader = new BufferedReader(stringReader);
//而下面的就有点特殊了,首先FileWriter也是获得数据的来源,接下来时bufferedWriter,这个比较特别:BufferedWriter不是FilterWriter的子类
//用bufferedWriter装饰FileWriter使其具有缓冲能力,PrintWriter更改FileWriter的行为,使其能够输出
//同时PrintWriter也是比较特殊的,它的构造器既能接受Writer对象,又能接受ouputStream对象。
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(file)));
//下面的就好懂了...
int lineCount = 1;
String s;
while((s = bufferedReader.readLine()) != null){
printWriter.println(lineCount++ +":"+s);
}
printWriter.close();
System.out.println(BufferedInputFile.read(file));
}
}
class BufferedInputFile {
public static String read(String fileName){
//reading input by lines
try {
//fileReader为获得数据的来源,具体的构造方法要多看API
//BufferedReader是使用readline()方法时的首先,其他情况第一选择是使用DataInputStream。很明显,它也是FilterInputStream。
FileReader fileReader = new FileReader(fileName);
BufferedReader bf = new BufferedReader(fileReader);
String s;
StringBuilder sb = new StringBuilder();
while((s=bf.readLine()) != null){
sb.append(s+"\n");
}
bf.close();
return sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
System.err.print("000");
}
return null;
}
public static void main(String[] args) {
System.out.println(read("D:\\private\\my_document\\文\\新建 文本文档.txt"));
}
}