プログラムをコンパイル、実行でウィンドウは正常に動作するんですが、
以下のエラーが出てテキストファイルが表示されないのですが、sample.txtの
パスが悪いようです。どこに置いたらいいか、どうしたらいいか教えてください。
ava.io.FileNotFoundException: sample4\sample.txt (指定されたパスが見つかりません。)
at java.io.FileInputStream.open0(Native Method)
...省略
package sample4; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class List4_13 extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L; JButton b1,b2; JTextArea ta; public List4_13() { this.setSize(400,300); ta = new JTextArea(); JScrollPane scroll = new JScrollPane(ta); this.add(scroll,BorderLayout.CENTER); b1 = new JButton("Load"); b1.addActionListener(this); b2 = new JButton("Save"); b2.addActionListener(this); JPanel p = new JPanel(); p.add(b1); p.add(b2); this.add(p,BorderLayout.SOUTH); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setVisible(true); } public static void main(String[] args) { new List4_13(); } public void actionPerformed(ActionEvent ev) { if(ev.getSource() == b1) this.load(); else if(ev.getSource() == b2) this.save(); } public void load() { FileReader fr = null; BufferedReader br = null; try { fr = new FileReader("sample4/sample.txt"); br = new BufferedReader(fr); String str = ""; String rstr = ""; while((rstr = br.readLine()) != null) str += rstr + "\r\n"; ta.setText(str); }catch(Exception ex) { ex.printStackTrace(); }finally { try { br.close(); }catch(Exception ex2) { ex2.printStackTrace(); } } } public void save(){ FileWriter fw = null; BufferedWriter bw = null; try { fw = new FileWriter("sample.txt"); bw = new BufferedWriter(fw); bw.write(ta.getText()); bw.flush(); }catch(Exception ex) { ex.printStackTrace(); }finally { try { bw.close(); }catch(Exception ex2) { ex2.printStackTrace(); } } } }
実行はどういった環境で行っていますか?Eclipse?コマンドプロンプト?
Eclipseです。ウインドウのボタン「load」をクリックするとたくさんのエラーが出ています。