2016-04-28 5 views
0

この割り当てを実行しようとしています。バイナリファイルを作成する方法

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

私のコード:私はこのエラー

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) 

私は完全な構文は、私に言っているのか理解していないに取得何らかの理由で

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); 
     } 


    } 
} 

。誰かが私の理解を助けることができるので、将来私は問題にぶつからない。この場合もバイナリファイルを作成します。それは私には見えない、ありがとう。

なぜ質問が重複としてマークされているのか分かりません。違います。これは私の個人的な割り当てと私のコードに間違っていることについての質問です。私はそれが重複している方法を見ていない。

+1

ディレクトリ 'src/text files /'を確認してください。 – saka1029

+0

'java.io.FileNotFoundExceptionのどの部分:src \ textファイル\ Exercise17_03.dat(システムは指定されたパスを見つけることができません)'は自明ではありませんか? –

+0

も参照してください:[Javaでファイルを作成してファイルに書き込む方法は?](http://stackoverflow.com/questions/2885173/how-to-create-a-file-and-write-to-a- file-in-java?rq = 1) –

答えて

-1

報告されているエラーは、この行である:

File file = new File("src/text files/Exercise17_03.dat"); 

あなたがそのファイル/フォルダがあることを想定している場所を示すために、「SRC」の前に何かを指定する必要があります。

-1

私はsrcディレクトリまたはそのtext filesサブディレクトリのいずれかがFileNotFoundExceptionFileOutputStreamコンストラクタからスローされているため、ランタイムは、から実行しているカレントディレクトリに相対存在しないことを推測します。

関連する問題