slisnychyi
slisnychyi

Reputation: 1980

Saving array into the file (Java)

I need to solve such task:

  1. Randomly generate the length of the array - save this int into file ("input.txt)" as a first digit;
  2. Randomly generate array elements - save each element into the file ("input.txt")

But the array elements won't save into file.

As I can see from console array has got digits, but they don't save into file.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) throws IOException {
    new Main().run();

    }

    Random rand;
    Scanner sc;
    PrintWriter pr, pr2;

    public void run() throws FileNotFoundException {
    pr2 = new PrintWriter(new File("input.txt"));
    pr = new PrintWriter(new File("output.txt"));
    rand = new Random();

    int a = rand.nextInt((int) Math.pow(10, 3));
    System.out.println(a);
    pr2.print(a);
    pr2.close();
    sc = new Scanner(new File("input.txt"));

    int[] arr = new int[a];

    for (int i = 0; i < arr.length; i++) {
        arr[i] = rand.nextInt((int) Math.pow(10, 3));

    }
    for (int i = 0; i < arr.length; i++) {
        System.out.println("" + i + ": " + arr[i]);
        pr2.print(arr[i]);

    }

    pr2.close();
    return;
    }

}

Upvotes: 0

Views: 285

Answers (2)

Spencer Ewall
Spencer Ewall

Reputation: 189

Your problem is that you're calling pr2.close() right after you write the length of the array. Once you close the PrintWriter, it will no longer allow anything to be written to the file; thus, when you later try to write the values in the array to pr2, pr2 says, "gosh, I know this guy wants me to write something but I'm closed, I just can't do it!" and so nothing gets written.

The PrintWriter works by storing all of your write(...) and print(...) calls into memory, and then actually writing them into your text file when you call the close() or flush() method. Although it's not necessary, if you wanted functional similarity to your current use of the first close() call, you could use flush() instead, but make sure that you do call close() when you are completely done using the Scanner (otherwise you're just asking for a memory leak).

Upvotes: 1

Mateusz
Mateusz

Reputation: 3048

You're closing the stream with pr2.close(); and then trying to print something through it. Then you close it again. Remove the first pr2.close(); And it should all work. Also you're having unnecessary Scanner object and second PrintWriter.

Upvotes: 1

Related Questions