Rose Rose - 1 month ago 6
Java Question

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);
}

Answer

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 + "|");