一个简单文件流问题
最近写了个程序,通过eclipse在盘中建一个任意文件,然后在eclipse中输入一段字符,关闭程序后可以保存在事先建好的文件中,可我这个程序总是在每一行显示第一行的内容,我不知道那里错了,请大家帮我看看.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class NewFileWriter {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// File f = new File("f:/c.txt");//建立文件
try {
FileOutputStream i = new FileOutputStream("f:/c.txt");// 建立文件
// -----------------------------------------
InputStreamReader l1 = new InputStreamReader(System.in);// 字节流转换为字符流
OutputStreamWriter l2 = new OutputStreamWriter(i);
BufferedReader m1 = new BufferedReader(l1);
BufferedWriter m2 = new BufferedWriter(l2);
String b = m1.readLine();
while (b != null) {
m2.write(b);
m2.newLine();
m2.flush();
m1.readLine();
}
m1.close();
m2.close();
l1.close();
l2.close();
i.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
[解决办法]
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class NewFileWriter {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// File f = new File("f:/c.txt");//建立文件
try {
FileOutputStream i = new FileOutputStream("f:/c.txt");// 建立文件
// -----------------------------------------
InputStreamReader l1 = new InputStreamReader(System.in);// 字节流转换为字符流
OutputStreamWriter l2 = new OutputStreamWriter(i);
BufferedReader m1 = new BufferedReader(l1);
BufferedWriter m2 = new BufferedWriter(l2);
String b = m1.readLine();
while (b != null) {
m2.write(b);
m2.newLine();
m2.flush();
m1.readLine(); //错误!应该是:b = m1.readLine();
}
m1.close();
m2.close();
l1.close();
l2.close();
i.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}