【问题标题】:how to create a binary file [duplicate]如何创建二进制文件[重复]
【发布时间】:2016-04-29 06:18:17
【问题描述】:

我正在尝试完成这项任务。

(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)

我不完全理解语法告诉我什么。有人可以帮助我理解,这样我以后就不会遇到问题。同样在此创建一个二进制文件。我觉得不合适,谢谢。

我不确定为什么该问题被标记为重复。那不一样。这是关于我的个人任务以及我的代码有什么问题的问题。我看不出它是如何复制的。

【问题讨论】:

  • 检查目录src/text files/是否存在。
  • java.io.FileNotFoundException: src\text files\Exercise17_03.dat (The system cannot find the path specified) 的哪一部分不是自我解释的?

标签: java syntax binary


【解决方案1】:

我猜src 目录或其text files 子目录不存在相对于运行时正在执行的当前目录,因为FileNotFoundException 是从FileOutputStream 构造函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 2020-01-07
    • 2020-08-03
    • 2017-12-24
    • 1970-01-01
    • 2019-02-28
    相关资源
    最近更新 更多