-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadWriteIO.java
More file actions
55 lines (49 loc) · 1.57 KB
/
ReadWriteIO.java
File metadata and controls
55 lines (49 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
Rahim Siddiq
May 26 2023
Write/Read Data
*/
import java.io.*;
import java.util.*;
public class ReadWriteIO
{
public static void main(String[] args) throws IOException
{
// Create a file object and check to see if it already exists
File file = new File("Exercise12_15.txt");
if (file.exists())
{
System.out.println("File already exists");
System.exit(1);
}
// Create PrintWriter object to write to file
PrintWriter output = new PrintWriter(file);
// New random object for generating random numbers
Random random = new Random();
// Loop uses both objects to write 100 random numbers to file
for (int i = 0; i < 100; i++)
{
output.print(random.nextInt() + " ");
}
// Close the file
output.close();
// Scanner object for reading data from file
Scanner scanner = new Scanner(file);
// Integer array called numbers to hold the data read from file
int[] numbers = new int[100];
// Loop to read data from file assigns each element to the index for numbers array
for (int i = 0; i < 100; i++)
{
numbers[i] = scanner.nextInt();
}
// Elements in array sorted using Arrays.sort() method
Arrays.sort(numbers);
// Loop to print sorted elements of the array
for (int number : numbers)
{
System.out.println(number);
}
// Close the scanner to prevent resource leak
scanner.close();
}
}