I am trying to do this assignment.
(Sum all the integers in a binary data file)
* create a binary data file named Exercise17_03.dat
* has been created and its data are created using writeInt(int)
* in DataOutputStream. The file contains an unspecified number
* of integers. Write a program to find the sum of the integers.
my code:
package loan;
import java.io.*;
public class Exercise17_03 {
public static void main(String[] args) throws IOException {
// Get the file for this exercise
File file = new File("src/text files/Exercise17_03.dat");
// if file doesn't exist create the file and write a random number of integers
if (!file.exists() || true) {
try (DataOutputStream out =
new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)))) {
int random = (int) (Math.random() * 200);
for (int i = 0; i < random; i++) {
out.writeInt((int)(Math.random() * 200));
}
}
}
// Read the file and display the sum
try (DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream(file)))) {
int sum = 0;
int count = input.available() / 4;
System.out.println(count);
while (count > 0) {
sum += input.readInt();
count--;
}
System.out.println("The sum is " + sum);
}
}
}
for some reason i get this error
Exception in thread "main" java.io.FileNotFoundException: src\text files\Exercise17_03.dat (The system cannot find the path specified)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at loan.Exercise17_03.main(Exercise17_03.java:24)
I do not completely understand what the syntax is telling me. Can someone help me understand so I do not run into the problem in the future. Also in this creating a binary file. It does not look right to me, thank you.
I am not sure why the question is marked as a duplicate. It is different. This is a question about my individual assignment and what is wrong with my code. I dont see how it is a duplicate.