user285372
user285372

Reputation:

Printing to File - Java beginner

I cannot figure out why the following simple program doesn't (create) and then write to a file? Can you spot where the problem is?

public class RandomSeq
{
    public static void main( String[] args)
    {
        // command-line argument
        int N = Integer.parseInt( args[0] );

        // generate and print N numbers between 0 and 1
        for ( int i = 0 ; i < N; i++ )
        {
            // System.out.println( Math.random() );
            StdOut.println( Math.random() );
        }
    }
}

When I type the following at the Interactions prompt:

java RandomSeq 5

0.9959531649155268
0.5010055704125982
0.4444779637605908
0.4205901267129799
0.09968268057133955

I obviously get the correct output, but when I use piping, it doesn't do what (I think) it should do:

> java RandomSeq 5 > f1.txt

Upvotes: 1

Views: 352

Answers (2)

posdef
posdef

Reputation: 6532

The "normal" Java way to write to a file is by using a Writer class. I denoted a small example below. Alternatively you can change the PrintStream that you write to which then sends the output to a file instead of the console (essentially the same as below)

PrintWriter out;
File myfile = new File(folder,"output.txt");
myfile.createNewFile();
fos = new FileOutputStream(myfile);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fos, "UTF-8")));
out.println("some text to go in the output file");

Edit: On my machine the code works fine using System.out.println(). I can only imagine that there might be a problem with the write permissions, else wise maybe StdOut object has some bugs...

~/scratch $ java RandomSeq 5 > out.txt
~/scratch $ cat out.txt 
0.5674462012296635
0.05189786036638799
0.1290205079541452
0.22015961731674394
0.6503198654182695
~/scratch $ 

Upvotes: 2

Shehzad
Shehzad

Reputation: 2940

I have tried with system.out and it works perfectly for me. There might be a possibility of read/Write permissions on your specific folder or directory because of which it is possible that you are unable to create f1.txt. Try to change the folder permissions or user rights if not proper rights are available. Also make sure that you are finding the file exactly at the same location where the program is creating.

Upvotes: 0

Related Questions