java 的实验写入文件:从标准设备中输入若干行英文句子直到输入“bye”结束,将这些字符串写入文件。

2024-12-03 00:34:32
推荐回答(2个)
回答1:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("D:/1.txt"));
System.out
.println("Please enter thecharacter what you want to write:");
String buf = br.readLine();
while (!buf.equals("bye")) {
bw.write(buf + "\r\n");
System.out
.println("Please enter thecharacter what you want to write:");
buf = br.readLine();
bw.flush();
}
System.out.println("Process completed!");
} catch (IOException e) {
e.printStackTrace();
}
}

}

我刚写的!!

回答2:

package test5;
import java.io.*;

public class test
{
public static void main(String[] args)throws java.io.IOException
{
InputStreamReader ir= new InputStreamReader(System.in);//将System.in转化为面向字符的流
BufferedReader in= new BufferedReader(ir);//为输入流提供缓冲区
FileWriter f =new FileWriter("test.txt");
BufferedWriter bw =new BufferedWriter(f);
String s;
System.out.print("请输入多行字符串\n");
while ((s = in.readLine())!=null)
{
if(s.equals("bye"))
{
break;
}
else
{
bw.write(s);
bw.newLine();
}
}
bw.close();
f.close();
in.close();
ir.close();
}
}