Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

file not found exception java?

public void actionPerformed(ActionEvent event) throws exception {

Object source = event.getSource();

if (source == b1)

this is where I tried to put it but error, and it wont let you read file without exception handler

import java.awt.BorderLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTextArea;

import java.io.*;

import java.util.Scanner;

import java.io.IOException;

public class ViewerFrame extends JFrame {

private JButton b1,b2;

private JTextArea field;

private JPanel panel, panel2;

public ViewerFrame(){

super.setTitle("My Reader");

b1 = new JButton("Open");

b2 = new JButton("Clear");

field = new JTextArea(25,25);

panel = new JPanel();

panel2 = new JPanel();

panel.add(b1);

panel.add(b2);

panel2.add(field,BorderLayout.CENTER);

add(panel, BorderLayout.NORTH);

add(panel2, BorderLayout.CENTER);

b1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

Object source = event.getSource();

if (source == b1)

{

String input = JOptionPane.showInputDialog(null, "Enter Input:", "Dialog for Input",

JOptionPane.QUESTION_MESSAGE);

setTitle(input);

FileReader fileR = new FileReader(input);

Scanner scan = new Scanner(fileR);

while (scan.hasNextLine() )

{

field.append(scan.nextLine());

}

}

}

}

);

b2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

Object source = event.getSource();

if (source == b2)

setTitle("My Reader");

field.setText( "");

}

}

);

}

}

1 Answer

Relevance
  • 1 decade ago
    Favorite Answer

    Yeah, any time you use a FileReader or something like it you actually need to surround it with a try-catch block. the Block part is what actually "catches" a thrown exception. So you need this:

    FileReader fileR = null; //make sure to declare this outside of the try-catch block!

    try {

    fileR = new FileReader(input);

    } catch (FileNotFoundException e1) {

    //if here, then do whatever it is that you need to do if the user put in a wrong file

    //also good to immediately exit out of the entire method. You do a silent return back to the caller

    return;

    }

Still have questions? Get your answers by asking now.