编写程序,随机生成10个1000~2000的整数,将它们写到文件data. dat 中,然后从该文件中读取这些整数,计算并输出这10个整数的和。要求使用 DatalnputStream 和DataOutputStream类编程。
时间: 2024-12-17 07:44:59 浏览: 23
在Java中,你可以按照以下步骤编写这个程序:
首先,我们需要创建一个文件并将随机生成的整数写入其中。这里我们先导入必要的库,并实现数据的写入操作:
```java
import java.io.*;
import java.util.Random;
public class WriteReadRandomNumbers {
public static void main(String[] args) {
String fileName = "data.dat";
Random random = new Random();
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
for (int i = 0; i < 10; i++) {
int num = random.nextInt(1001) + 1000;
writer.write(num + "\n");
}
System.out.println("Numbers written to file successfully.");
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
}
}
```
接着,我们需要编写另一个部分来从文件中读取这些整数并计算其和:
```java
public static void readAndCalculateSum(String fileName) {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName));
DataInputStream dis = new DataInputStream(new FileInputStream(fileName))) {
int sum = 0;
String line;
while ((line = reader.readLine()) != null) {
sum += Integer.parseInt(line);
}
// Convert DataInputStream to int for sum calculation
while (dis.available() > 0) {
sum += dis.readInt();
}
System.out.printf("The sum of the numbers in the file is: %d%n", sum);
} catch (IOException e) {
System.err.println("Error reading from or calculating sum: " + e.getMessage());
}
}
// Call the read function after writing
public static void main(String[] args) {
WriteReadRandomNumbers.writeRandomNumbersToFile();
readAndCalculateSum("data.dat");
}
```
在这个程序中,`writeRandomNumbersToFile`方法用于写入10个随机数到文件,而`readAndCalculateSum`方法负责读取这些数字并计算总和。这两个方法都在`main`函数中调用。
阅读全文