мне нужно решить такую задачу:Сохранение массива в файл (Java)
- Случайных генерировать длину массива - сохранить эту Int в файл («input.txt)» в качестве первой цифры ;
- Случайным генерировать элементы массива - сохранить каждый элемент в файл («input.txt»)
Но элементы массива не будет сохранять в файл.
Как я могу видеть из массива консоли, есть цифры, но они не сохраняются в файле.
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;
}
}
Вы закрываете pr2, а затем пытаетесь написать ему. Избавьтесь от инструкции перед sc = new Scanner (новый файл («input.txt»)), который закрывает запись. –