- Java code
public static void main(String[] args) throws IOException { FileWriter fw = new FileWriter("c:/s1.txt"); BufferedWriter bw = new BufferedWriter(fw); FileReader fr = new FileReader("c:/s1.txt"); BufferedReader br = new BufferedReader(fr); FileWriter fw2 = new FileWriter("c:/s2.txt"); BufferedWriter bw2 = new BufferedWriter(fw); bw.write("明月几时有,把酒问青天。");//尝试将这一句改为 bw.write("明月几时有,把酒问青天。\n");//却没有实现换行,为什么? bw.newLine(); bw.write("不知天上宫阙,今夕是何年。"); System.out.println("Copying in progress......"); while(br.ready()){ bw2.write(br.readLine()); }//通过上面的循环,本意是将s1.txt中的文字复制到s2.txt中的,结果,发现s2文件为空!!//经过调试发现,原来br.readline()竟然为null!!为什么?? System.out.println("Success!"); bw.close(); fw.close(); fr.close(); br.close(); bw2.close(); fw2.close(); }
------解决方案--------------------
- Java code
public static void main(String[] args) throws IOException { FileWriter fw = new FileWriter("c:/s1.txt"); BufferedWriter bw = new BufferedWriter(fw); bw.write("明月几时有,把酒问青天。\r\n");//改为\r\n bw.write("不知天上宫阙,今夕是何年。"); bw.close();//用完了就将它关闭,如果你是懒人,可以只关闭最外层流i //重新打开它 FileReader fr = new FileReader("c:/s1.txt"); BufferedReader br = new BufferedReader(fr); FileWriter fw2 = new FileWriter("c:/s2.txt"); BufferedWriter bw2 = new BufferedWriter(fw2);//写错了fw2 while (br.ready()) { bw2.write(br.readLine()); bw2.newLine();//添加换行符 } bw2.close();//通常先关闭写,再关闭读 br.close(); }
------解决方案--------------------
- Java code
import java.io.*;public class FileWriterDemo { public static void main(String[] args) throws IOException { FileWriter fw = new FileWriter("c:/s1.txt"); BufferedWriter bw = new BufferedWriter(fw); bw.write("明月几时有,把酒问青天。\r\n");//尝试将这一句改为 bw.write("明月几时有,把酒问青天。\n");//却没有实现换行,为什么? windows加上\r就可以了// bw.newLine(); bw.write("不知天上宫阙,今夕是何年。"); System.out.println("Copying in progress......"); bw.close();//先保证内容写到文件 FileReader fr = new FileReader("c:/s1.txt"); BufferedReader br = new BufferedReader(fr); FileWriter fw2 = new FileWriter("c:/s2.txt"); BufferedWriter bw2 = new BufferedWriter(fw2); //这里更改,原来是fw// while(br.ready()){// bw2.write(br.readLine());// } 复制内容的API调用有问题 看下面的 String str=""; while((str=br.readLine())!=null){ bw2.write(str); }//通过上面的循环,本意是将s1.txt中的文字复制到s2.txt中的,结果,发现s2文件为空!!//经过调试发现,原来br.readline()竟然为null!!为什么?? System.out.println("Success!"); bw2.close(); br.close(); }}
------解决方案--------------------
bw.write("明月几时有,把酒问青天。\r\n");
再加上一个“\r”