GTU OOP Program - 21
21). Write a program to create a file name 123.txt, if it does not exist. Append a new data to it if it already exist. write 150 integers created randomly into the file using Text I/O. Integers are separated by space.
- import java.io.*;
- public class Program_21 {
- public static void main(String[] args) {
- File file = new File("program_21.txt");
- if (file.exists()) {
- System.out.println("File already exists");
- System.exit(0);
- }
- try (PrintWriter output = new PrintWriter(file);) {
- // writing 150 integers created randomly to file
- for (int i = 0; i < 150; i++) {
- output.print(((int) (Math.random() * 400) + 1) + " ");
- }
- System.out.println("File program_21.txt created Succesfully!");
- } catch (FileNotFoundException fnfe) {
- System.out.println("Cannot create the file");
- fnfe.printStackTrace();
- }
- }
- }
Output
Comments