1

だから私はJava初心者で、ファイルをいじり始めました。私が知っているタイプのデータを含むファイル「tes.t」があるとします。それらがint-double-int-doubleなどであると仮定します。内部のそのようなペアの数はわかりませんが、入力が終了したことを確認するにはどうすればよいですか?私の現在の知識のために、私はこのようなことを考えました:

try{
        DataInputStream reading = new DataInputStream(new FileInputStream("tes.t"));
        while(true)
        {
            System.out.println(reading.readInt());
            System.out.println(reading.readDouble());
        }
        }catch(IOException xxx){}
}

しかし、ここでのこの無限ループは、私をどういうわけか不快にさせます。つまり、入力が終了するとすぐにIOExceptionがキャッチされるはずですが、それが適切な方法かどうかはわかりません。これを行うためのより良い方法はありますか?というか、私のものは悪いと確信しているので、より良いアプローチは何ですか:)

4

4 に答える 4

3

ファイルにはint-doubleペアがあるため、次のように実行できます。

DataInputStream dis = null;
try {
    dis = new DataInputStream(new FileInputStream("tes.t"));
    int i = -1;
    // readInt() returns -1 if end of file...
    while ((i=dis.readInt()) != -1) {
        System.out.println(i);
        // since int is read, it must have double also..
        System.out.println(dis.readDouble());
    }

} catch (EOFException e) {
    // do nothing, EOF reached

} catch (IOException e) {
    // handle it

} finally {
    if (dis != null) {
        try {
            dis.close();

        } catch (IOException e) {
             // handle it
        }
    }
}
于 2012-11-06T19:53:32.197 に答える
2

次のようなことができます。

try{
  FileInputStream fstream = new FileInputStream("tes.t");
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   {
  System.out.println (strLine);
  }
  //Close the input stream
  in.close();
  }catch (IOException e){//Catch exception if any
 System.err.println("Error: " + e.getMessage());
 }

注:このコードはテストされていません。

于 2012-11-06T19:38:13.037 に答える
1

これはjavadocからのものです:

スロー:EOFException-4バイトを読み取る前にこの入力ストリームが最後に到達した場合。

EOFExceptionこれは、EOFに到達したことを確認するためにキャッチできることを意味します。ファイルが完全に読み取られたことを示す、ある種のアプリケーションレベルマーカーを追加することもできます。

于 2012-11-06T19:35:59.127 に答える
0

これはどう:

DataInputStream dis = null;
try {
    dis = new DataInputStream(new FileInputStream("tes.t"));
    while (true) {
        System.out.println(dis.readInt());
        System.out.println(dis.readDouble());
    }

} catch (EOFException e) {
    // do nothing, EOF reached

} catch (IOException e) {
    // handle it

} finally {
    if (dis != null) {
        try {
            dis.close();

        } catch (IOException e) {
            // handle it
        }
    }
}
于 2012-11-06T19:41:38.043 に答える