Rose
Rose

Reputation: 35

Write data in file using java that data was returned by function

I want to write data in file that data is returned by another function.

I can see all the values in console but not in the file. Any idea? Thanks

for (int dx = 1; dx <= 100; dx++) {

    try {

        File file = new File("file.txt");
        file.createNewFile();

        FileWriter write = new FileWriter(file);

        String sizeX = (String.valueOf(Myclass.myFunction(a, b));

        write.write(sizeX);
        write.flush();
        write.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

private static Random random = new Random();

public static int myFunction(int a, int b) {
    return (int) (random.myFunction(a*b);
}

Upvotes: 2

Views: 71

Answers (2)

marcelovca90
marcelovca90

Reputation: 2804

Create, flush and close your file outside the for loop, but inside the try/catch block.

    try {

        File file = new File("file.txt");
        file.createNewFile();

        FileWriter writer = new FileWriter(file);

        for (int dx = 1; dx <= 100; dx++) {
            String sizeX = (String.valueOf(Myclass.myFunction(a, b));
            writer.write(sizeX);
        }

        writer.flush();
        writer.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

private static Random random = new Random();

public static int myFunction(int a, int b){
    return (int) (random.myFunction(a*b);
}

You might want to put a separator between the numbers to make the output more legible, i.e.:

writer.write(sizeX + "|");

Upvotes: 2

Iofacture
Iofacture

Reputation: 685

I think this is more like what you are trying to accomplish

EDIT - Looks like someone already beat me to it!

To add to his answer below, he is correct you should not make a call to flush inside the loop as I have written below. Here is a good explanation as to why:

Here in this SO post

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

public class test
{

    private static Random randomFunction = new Random();

    public static void main(String[] args) throws IOException
    {

        FileWriter write = null;

        try
        {
            File file = new File("file.txt");
            file.createNewFile();
            write = new FileWriter(file);

            for (int dx = 1; dx <= 100; dx++)
            {
                String sizeX = String.valueOf(myFunction(34, 43));
                write.append(sizeX);
                write.flush();
            }

        }
        catch (IOException e)
        {
            e.printStackTrace();
            throw e;
        }

        try
        {
            write.close();
        }
        catch (Exception x)
        {
            x.printStackTrace();
        }
    }

    public static int myFunction(int a, int b)
    {
        return randomFunction.nextInt((a * b));
    }

}

Upvotes: 0

Related Questions