Question
Java Programming I' am having this error. Need help, please. thanks Exception in thread main java.io.IOException: Stream closed at java.base/java.io.BufferedReader.ensureOpen(BufferedReader.java:122) at java.base/java.io.BufferedReader.readLine(BufferedReader.java:319) at java.base/java.io.BufferedReader.readLine(BufferedReader.java:392) at
Java Programming
I' am having this error. Need help, please. thanks
Exception in thread "main" java.io.IOException: Stream closed at java.base/java.io.BufferedReader.ensureOpen(BufferedReader.java:122) at java.base/java.io.BufferedReader.readLine(BufferedReader.java:319) at java.base/java.io.BufferedReader.readLine(BufferedReader.java:392) at CreateWriteReadFile.main(CreateWriteReadFile.java:42)
Here is the instruction
Program 2: Write a program to create a new file titled data.file, if the file does not exist. Then write to the new file, adding 10 randomly generated numbers, or append 10 randomly generated numbers to a previous file. Each integer is to be separated by a space. Close the file, then reopen the file and read the data from the file and display it.
Here is my code
import java.util.*;
import java.io.*;
public class CreateWriteReadFile {
public static void main(String[] args) throws IOException{
try{
//check if file exixsts. If not create file
File file = new File("data.file.txt");
if (file.exists()){
System.out.println("File already exists. ");
}
else {file.createNewFile();
System.out.println("File is created. ");}
//write to file
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fileWriter);
Random random = new Random();
for (int i = 0; i <10; i++ ){
int num = random.nextInt(100);
bw.write(num + " ");
}
bw.write(" ");
bw.close();
fileWriter.close();}
catch(IOException e){
e.printStackTrace();
}
//read from file
try{
File file = new File("data.file.txt");
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
String line;
System.out.println("Data from file ");
while ((line = br.readLine()) != null){
System.out.println(line);
br.close();
}
fileReader.close();
}
catch (FileNotFoundException e){
System.out.println("Error" + e);
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started