2016-05-09 12 views
0

私はファイルを読み込む入力ファイルストリームメソッドを持っていますが、別のメソッドでそのファイルを使用する方法がわかりません。このファイルには、UTF文字列と2つの整数があります。メインメソッドでこれらの異なるintまたはstringのそれぞれを使用するにはどうすればよいですか?私は3つの異なる変数をコンソールに出力したいと言いますが、どうすればそれをやりますか?Java I/O FileStreamの問題

public static dataStreams() throws IOException { 
    int i = 0; 
    char c; 
    try (DataInputStream input = new DataInputStream(
      new FileInputStream("input.dat")); 
    ) { 

     while((i=input.read())!=-1){ 
      // converts integer to character 
      c=(char)i; 
     } 

     return c; 
     return i; 
    /* 
     String stringUTF = input.readUTF(); 
     int firstInt = input.readInt(); 
     int secondInt = input.readInt(); 
     */ 


    } 


} 
+0

は、多分あなたはこれらのプロパティを持つオブジェクトを作成することができ、1つの文字列と2 int型ここで私はこの方法で試したいくつかのことです – OscarBcn

+0

この後、dataStreamsを宣言した後、他のメソッドで「Unhanded exception type IOException」というエラーが発生しましたが、何が問題なのでしょうか?ありがとう – Jake

+0

その理由は、有効な質問です。 – TriCore

答えて

1

たぶん、このようなこれらのプロパティのための1つの容器、::

public static void main(String [] args) { 
     DataContainer dContainer = null; 
    try { 
     dContainer = dataStreams(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    //do some logging with properties 
    System.out.println(dContainer.getFirst()); 
    System.out.println(dContainer.getSecond()); 
    System.out.println(dContainer.getUtf()); 
    } 

    public static DataContainer dataStreams() throws IOException { 
     int i = 0; 
     char c; 
     try (DataInputStream input = new DataInputStream(
       new FileInputStream("input.dat")); 
     ) { 

      while((i=input.read())!=-1){ 
       // converts integer to character 
       c=(char)i; 
      } 



      String stringUTF = input.readUTF(); 
      int firstInt = input.readInt(); 
      int secondInt = input.readInt(); 

      DataContainer dContainer = new DataContainer(stringUTF, firstInt, secondInt); 
      return dContainer; 
     } 


    } 

    static class DataContainer { 
     String utf; 
     int first; 
     int second; 
     DataContainer(String utf, int first, int second) { 
      this.utf = utf; 
      this.first = first; 
      this.second = second; 
     } 
     public String getUtf() { 
      return utf; 
     } 
     public int getFirst() { 
      return first; 
     } 
     public int getSecond() { 
      return second; 
     } 

    } 
+0

私はオブジェクトを使って同様のことを書いていますが、他のメソッドでdataStremsの変数を宣言すると、 "Unhanded exception type IOException"というエラーが発生します。これは私が今立ち往生している場所です。 – Jake

+1

確かに、あなたはその例外をスローしているので、あなたのdataStreamsメソッドでtry-catchを使う必要があります – OscarBcn

+0

私はtry-catchを追加しました – OscarBcn