Part A Write a program to create a file named Lab13.txt if the file does not exi
ID: 3689884 • Letter: P
Question
Part A
Write a program to create a file named Lab13.txt if the file does not exist (If the file exists, terminate your program without doing anything.) Write ten integers ranging [0, 99] created randomly into the file using text I/O. Integers are separated by spaces in the file. Read the data back from the file and display them on the console.
Part B
Write a second program to create a file named Lab13_scale.txt if it does not exist (if the file exists, terminate your program without doing anything.). Multiply all the numbers from Lab13.txt by 10 and save all the new numbers in Lab13_scale.txt. For example, if Lab13.txt is
Explanation / Answer
import java.io.*;
public class Lab13
{
public static void main(String ar[])
{
String toWrite = "";
int x = 0;
try
{
File file = new File("Lab13.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(filewriter);
for (int i = 0; i < 10; i++)
{
x = (int) (Math.random() * 100);
writer.write(" " + x);
}
writer.close();
} catch (IOException e)
{
e.printStackTrace();
}
try
{
File file1 = new File("Lab13.txt");
FileReader filereader = new FileReader(file1);
BufferedReader reader = new BufferedReader(filereader);
String y;
while ((y = reader.readLine()) != null)
{
////////////////////////////////////////
//trim - delete leading spaces from y
String[] array = y.trim().split(" ");
for (int i = 0; i < array.length; i++)
{
int number = Integer.parseInt(array[i]);
System.out.println(number);
toWrite += (number * 10 + " ");
}
System.out.println(toWrite);
////////////////////////////////////////
}
File output = new File("lab13_scale.txt");
if (!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter = new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
Lab13.txt
69
23
34
89
59
8
27
57
47
96
lab13_scale.txt
690 230 340 890 590 80 270 570 470 960
sample output
69
23
34
89
59
8
27
57
47
96
690 230 340 890 590 80 270 570 470 960