Results 1 to 5 of 5

Thread: write to file

  1. #1
    Ike
    Ike is offline Member
    Join Date
    Aug 2011
    Posts
    21
    Rep Power
    0

    Default write to file

    Is there any simple command to have .TXT file with all the data that comes out in the output screen?

    Like instead of: System.out.printn > System.out.printfile or whatever?

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: write to file

    PrintStreams (which is what System.out is an instance of) can be created manually with a FileOutputStream as its base.

  3. #3
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: write to file

    Note, however, that PrintStreams ignore errors.

    Edit: Also note that System has a setOut method. I wonder, in combination to what was posted earlier, that might do.

  4. #4
    Ike
    Ike is offline Member
    Join Date
    Aug 2011
    Posts
    21
    Rep Power
    0

    Default Re: write to file

    Hmm, I found an example. Since there will be thousands of numbers in the output, are you think FileOutputStream is the method to use?
    All those try/catch, open/close will not slow/mess down things?


    Java Code:
    import java.io.*;
    
    class PrintStreamDemo {  
       public static void main(String args[]){ 
        FileOutputStream out; 
      PrintStream ps; // declare a print stream object
      try {
     // Create a new file output stream
      out = new FileOutputStream("myfile.txt");
    
      // Connect print stream to the output stream
      ps = new PrintStream(out);
      
      ps.println ("This data is written to a file:");
      System.err.println ("Write successfully");
      ps.close();
      }
      catch (Exception e){
      System.err.println ("Error in writing to file");
      }
       }
    }

  5. #5
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,784
    Rep Power
    7

    Default Re: write to file

    Another option is to use the command line.
    Java Code:
    java MyProgram > output.txt
    The shell will redirect any output to the file instead of the screen.

    This is also useful for input during testing.
    Java Code:
    java MyProgram < input.txt
    And of course the two can be combined.
    Java Code:
    java MyProgram < input.txt > output.txt

Similar Threads

  1. Text read and write between *.txt file and *.xls file
    By lemontree45 in forum New To Java
    Replies: 6
    Last Post: 08-12-2011, 02:08 AM
  2. Replies: 6
    Last Post: 12-01-2010, 05:31 AM
  3. Replies: 8
    Last Post: 05-12-2010, 07:19 PM
  4. Replies: 5
    Last Post: 02-05-2009, 10:28 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •