我正在尝试做这个任务。
(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.
我的代码:
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);
}
}
}
出于某种原因我收到此错误
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)
我不完全理解语法告诉我的内容。有人可以帮助我理解,所以我将来不会遇到这个问题。还在此创建一个二进制文件。这对我来说不合适,谢谢。
我不确定为什么这个问题被标记为重复。那不一样。这是关于我的个人作业以及我的代码有什么问题的问题。我不知道它是如何复制的。
答案 0 :(得分:-1)
报告的错误在此行中:
{{1}}
您需要在&#34; src&#34;之前指定一些内容。指出该文件/文件夹的位置。
答案 1 :(得分:-1)
我猜想src
目录或其text files
子目录不存在相对于运行时正在执行的当前目录,因为{{1}正在从FileNotFoundException
构造函数抛出。