请问这个程序我想输出到文件而不是控制台,要怎么做
1个回答
展开全部
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
public class TestReplace {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("1.txt"));
StringBuilder text = new StringBuilder(); // 消息对象
String tmp = ""; // 单行字符
while ((tmp = in.readLine()) != null) {
if (tmp.matches("^[0-9]+$")) { // 当本行是以数字开头后面紧跟换行
text.append("\n" + tmp);
} else {
text.append("," + tmp);
}
}
text.replace(0, 1, ""); // 替换掉第一个换行
FileOutputStream out = new FileOutputStream("2.txt");
byte[] buff = text.toString().getBytes();
out.write(buff);
out.flush();
}
}
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
public class TestReplace {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("1.txt"));
StringBuilder text = new StringBuilder(); // 消息对象
String tmp = ""; // 单行字符
while ((tmp = in.readLine()) != null) {
if (tmp.matches("^[0-9]+$")) { // 当本行是以数字开头后面紧跟换行
text.append("\n" + tmp);
} else {
text.append("," + tmp);
}
}
text.replace(0, 1, ""); // 替换掉第一个换行
FileOutputStream out = new FileOutputStream("2.txt");
byte[] buff = text.toString().getBytes();
out.write(buff);
out.flush();
}
}
来自:求助得到的回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询