2016-04-25 10 views
0

私は、ボタンをクリックしてWindowBuilderを使用して、テキストファイルのデータをJListにロードしようとしています。下のコードからわかるように、私は修正できないような例外はほとんどありません。 java.io.FileReaderをインポートすることは役に立ちません。GUI IOExceptionのスイングとFileNotFoundException

私は自分のスコアベクトルのコードを持つ別のクラスファイルを持っています。

JButton btnLoadData = new JButton("Load Data"); 
    btnLoadData.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 

      String sLine; 

      Vector<Score> scoreVec = new Vector<Score>(); 

      //Here I am getting a FileNotFoundException for (new FileReader("scores.txt") 
      BufferedReader in = new BufferedReader(new FileReader("scores.txt")); 


      //Here I am getting an IOException for in.readLine() 
      while ((sLine = in.readLine()) != null) 
      { 
       scoreVec.addElement(new Score(sLine)); 
      } 

      //this is also throwing an IOException 
      in.close(); 


      //Placeholders until I get the rest of the program working 
      System.out.println(scoreVec.get(1).name); 
      System.out.println(scoreVec.get(1).country); 
     } 
    }); 
    btnLoadData.setBounds(10, 227, 89, 23); 
    frame.getContentPane().add(btnLoadData); 
+0

'新規FileReader( "scores.txtは")'入れを参照してください。可読性が保証されている安定したパスの(サブディレクトリ)の高得点。そのパスは** 'user.home' **です。 –

答えて

1

...

public void actionPerformed(ActionEvent arg0) { 

    String sLine; 

    Vector<Score> scoreVec = new Vector<Score>(); 

    //Here I am getting a FileNotFoundException for (new FileReader("scores.txt") 
    try (BufferedReader in = new BufferedReader(new FileReader("scores.txt"))) { 

     //Here I am getting an IOException for in.readLine() 
     while ((sLine = in.readLine()) != null) { 
      scoreVec.addElement(new Score(sLine)); 
     } 

    } catch (IOException exp) { 
     exp.printStackTrace(); 
    } 

    //Placeholders until I get the rest of the program working 
    System.out.println(scoreVec.get(1).name); 
    System.out.println(scoreVec.get(1).country); 
} 

は詳細についてExceptions trailThe try-with-resources Statement

0

何の関連するクラスの実際のパスであると私はrecommentだけあなたがscores.txtファイルの完全なパスを使用することができるものではない

をscores.txt。あなたは、たとえば、発生した例外をキャッチして処理する必要が

+0

scores.txtはsrcフォルダの1つ上のフォルダです(メインプロジェクトフォルダと同じですか?) – RThomP

+0

相対パスは問題なく、プログラムをより柔軟にしますが、プログラムの実行場所の変更方法に注意する必要があります – MadProgrammer

関連する問題