Create your own data file consisting of integer, double or String values. Create
ID: 3581766 • Letter: C
Question
Create your own data file consisting of integer, double or String values. Create your own unique Java application to read all data from the file echoing the data to standard output. After all data has been read, display how many data were read. For example, if 10 integers were read, the application should display all 10 integers and at the end of the output, print "10 data values were read" Demonstrate your code compiles and runs without issue. Also enhance this code to write the summary output to a file instead of standard output.
Explanation / Answer
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class ReadDataFile {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(new File("input.txt"));
int count = 0;
File file = new File("output.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
while (scanner.hasNext()) {
String value = scanner.next();
count++;
System.out.println(value);
// Writes the content to the file
writer.write(value + " ");
}
System.out.println(count + " data values were read");
writer.write(count + " data values were read");
writer.flush();
writer.close();
} catch (Exception e) {
// TODO: handle exception
} finally {
if (scanner != null)
scanner.close();
}
}
}
input.txt
3 4
6 4
3 6
2 5
2 6
output.txt
3
4
6
4
3
6
2
5
2
6
10 data values were read
OUTPUT:
3
4
6
4
3
6
2
5
2
6
10 data values were read
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.