求帮助怎么样用printStream类在e.txt中写上一首唐诗呢且是从键盘输入的

QEC568320642 2011-12-19 10:21:13
求助我只会用printWriter的不符合题目要求
...全文
171 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiongyu2006 2011-12-20
  • 打赏
  • 举报
回复

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

public class Ansewer29
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
File file = new File("d:" + File.separator + "e.txt");
FileOutputStream fout = null;
try
{
fout = new FileOutputStream(file);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
PrintStream ps = null;
try
{
ps = new PrintStream(fout, true, "GBK");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Scanner sc = new Scanner(System.in);
String str = null;
System.out.println("请输入古诗,按'q'退出!");

while (sc.hasNextLine())
{
str = sc.nextLine();
if (str.equals("q"))
{
System.out.println("退出,Bye");
break;
}
ps.println(str);
}
try
{
fout.close();
}
catch (IOException e)
{
e.printStackTrace();
}
ps.close();
}
}
regerfe 2011-12-20
  • 打赏
  • 举报
回复

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

public class PrintPoem
{
public static void main(String[] args)
{
try
{

PrintStream out = new PrintStream("e.txt","GBK");
String poem = "床前明月光,\r\n疑是地上霜。\r\n举头望明月,\r\n低头思故乡。";
out.print(poem);
out.close();

Scanner in = new Scanner(new File("e.txt"));
while(in.hasNextLine())
{
System.out.println(in.next());
}
in.close();

} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}

phqqhaha 2011-12-20
  • 打赏
  • 举报
回复
还有是System.in 不是System.io
phqqhaha 2011-12-20
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 huntor 的回复:]

使用 java.util.Scanner 读入
使用 java.io.PrintStream 输出

PrintStream out = new PrintStream("e.txt", "GBK");
Scanner scanner = new Scanner(System.io);
while(scanner.hasNextLine()){
out.println(sca……
[/Quote]

这个有问题呀。。好像必须要catch exception才行。。。 还有 怎么关闭呢?一直在读取状态除非停止程序
huntor 2011-12-19
  • 打赏
  • 举报
回复
使用 java.util.Scanner 读入
使用 java.io.PrintStream 输出

PrintStream out = new PrintStream("e.txt", "GBK");
Scanner scanner = new Scanner(System.io);
while(scanner.hasNextLine()){
out.println(scanner.nextLine());
}
out.flush();
scanner.close();
out.close();

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧