黑马程序员技术交流社区

标题: 大家给我看看这个我运行的结果 指定文件架 里面 啥都没有 [打印本页]

作者: chocolate    时间: 2012-1-5 14:31
标题: 大家给我看看这个我运行的结果 指定文件架 里面 啥都没有
本帖最后由 chocolate 于 2012-1-5 20:12 编辑

import java.io.*;
public class myTest_18{
        public static void main(String []ars){
                BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                String s=new String("");
            //while(true){
            
                try{
                        PrintStream out=new PrintStream(new FileOutputStream("my.txt"));
                        s=br.readLine();
                        //if(s.equals("quit")){  //输入quit退出
                                //break;
                        //}
                        System.setOut(out);
                        System.out.println(s);
                }
                catch(FileNotFoundException e){
                        System.err.print("file not found");
                }
                catch(IOException e){
                        e.printStackTrace();
                }
          // }
        }
}



作者: 刘基军    时间: 2012-1-5 14:53
输入输出流都没有关闭。
作者: 李建平    时间: 2012-1-5 15:04
因为你的 PrintStream out=new PrintStream(new FileOutputStream("my.txt")); 是创建在循环里头的,你每输入一次的时候就重新创建了一次输出流,最后输入"quit"的时候就直接跳出了没有写入任何东西所以文件里头没东西
改1:PrintStream out=new PrintStream(new FileOutputStream("my.txt",true));
改2:把PrintStream out=new PrintStream(new FileOutputStream("my.txt"));定义到循环外面
作者: 周吉明    时间: 2012-1-5 15:28
我用myeclipse测试了一下,程序没有问题,可以正确运行。在键盘输入的内容都存到了my.txt文件中,你在存放MyTest_18.class的文件夹里找找。
另外 public class myTest_18 // 一般类名首字母大写 MyTest_18  
最后要有finally 关闭缓冲区。

作者: 小白    时间: 2012-1-6 17:37
没有close()啊!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2