本帖最后由 fanshuai 于 2015-3-30 21:45 编辑
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Writer;
import java.io.Reader;
public class Test{
public static void main(String... args) throws IOException{
//将"sfhwi\ni\rfsf\r\nuhk"写入硬盘文件
Writer w=new FileWriter("C:\\1.Java");
w.write("sfhwi\ni\rfsf\r\nuhk");
w.close();
//调用自己写的程序将"sfhwi\ni\rfsf\r\nuhk"写入另一个硬盘文件
Reader r = new FileReader("C:\\1.Java");
BufferedWriter bw=new BufferedWriter(new FileWriter("C:\\2.Java"));
MyBufferedReader br = new MyBufferedReader(r);
for(String line =null;(line=br.myReadLine())!=null;){
bw.write(line);
bw.newLine();
bw.flush();
}
br.myClose();
bw.close();
}
}
class MyBufferedReader{
private Reader r;
MyBufferedReader(Reader r){
this.r=r;
}
public String myReadLine() throws IOException{
/*
定义一个临时容器,原BufferedReader封装的是字符数组
为了方便,定义一个StringBuilder容器,因为最终还是要将数据变成字符串
*/
StringBuilder sb = new StringBuilder ();
int len = 0;
while((len = r.read())!=-1){
if(len=='\r')
continue;
if(len=='\n')
return sb.toString();
else
sb.append((char)len);
}
//防止最后一行没有换行的情况
if(sb.length()!=0)
return sb.toString();
else
return null;
}
public void myClose() throws IOException{
r.close();
}
}
|