标准输入流为键盘,标准输出流为显示器。
在Java语言中,如何重定向到普通的2个文件,in.txt和out.txt
请给出代码示例

解决方案 »

  1.   

    // All writes to this print stream are copied to two print streams
        public class TeeStream extends PrintStream {
            PrintStream out;
            public TeeStream(PrintStream out1, PrintStream out2) {
                super(out1);
                this.out = out2;
            }
            public void write(byte buf[], int off, int len) {
                try {
                    super.write(buf, off, len);
                    out.write(buf, off, len);
                } catch (Exception e) {
                }
            }
            public void flush() {
                super.flush();
                out.flush();
            }
        }Here's an example that uses the class:    
        try {
            // Tee standard output
            PrintStream out = new PrintStream(new FileOutputStream("out.log"));
            PrintStream tee = new TeeStream(System.out, out);
        
            System.setOut(tee);
        
            // Tee standard error
            PrintStream err = new PrintStream(new FileOutputStream("err.log"));
            tee = new TeeStream(System.err, err);
        
            System.setErr(tee);
        } catch (FileNotFoundException e) {
        }
        
        // Write to standard output and error and the log files
        System.out.println("welcome");
        System.err.println("error");
      

  2.   

     File infile = new File("d:\\in.txt");   
     
    File outFile = new File("d:\\out.txt");  InputStream input = new FileInputStream(file);        
                                               
     
    OutputStream Out=new FileOutputStream(zipFile);      int temp = 0;                                      while ((temp = input.read()) != -1) {                Out.write(temp);                        }  
             input.close();                           
     
             Out.close();   
      

  3.   

    变量写错了,再来一次
         File infile = new File("d:\\in.txt"); 
         File outFile = new File("d:\\out.txt"); 
         InputStream input = new FileInputStream(infile);                                                 
         OutputStream out=new FileOutputStream(outFile);     
         int temp = 0;                          
         while ((temp = input.read()) != -1) { 
                     out.write(temp);             
                 } 
          input.close();                         
          out.close(); 
      

  4.   

    try this:System.setOut(
        new PrintStream(
            new FileOutputStream("C:\\out.txt")
        )
    );
    System.setIn(
        new FileInputStream("C:\\in.txt")
    );