0
package lab6;
import javax.swing.*;
import java.io.*;
import java.util.*;
import javax.swing.filechooser.*;

public class FileReading {

public static void main(String[] args) {
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Lab 6 (Select a file to read) - CSC 120 Josh Peel");
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
        "TXT - text files", "txt");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(null);

    if (returnVal == JFileChooser.APPROVE_OPTION){ //user picked something
        FileReader myReader = new FileReader(chooser.getSelectedFile().getAbsolutePath());
    }
    else{
        System.exit(0);
    }

gives me the error:

Exception in thread "main" java.lang.Error:
Unresolved compilation problem: 
Unhandled exception type FileNotFoundException

at lab6.FileReading.main(FileReading.java:15)

so I'm not quite sure how to bind the file chosen with jfilechooser to my file reader... I do not want to hardcode the file paths but am having a brainfart on a more universal apporach

still getting the same error with

 if (returnVal == JFileChooser.APPROVE_OPTION){ //user picked something
        String myChoice = chooser.getSelectedFile().getAbsolutePath();
        FileReader myReader = new FileReader(myChoice);

as well as

 if (returnVal == JFileChooser.APPROVE_OPTION){ //user picked something
        File myChoice = chooser.getSelectedFile();
        FileReader myReader = new FileReader(myChoice);
Josh Peel
  • 87
  • 1
  • 10
  • `still getting the same error with..` - and did you display the file name? Is the path complete? Again do some basic debugging. – camickr Sep 29 '15 at 19:57
  • yes. the code does not fail if I simply select a file and output the file path but when I add the line creating my file reader, it will no longer compile and run. and the file path is complete (C:\Java\input.txt) also the method getAbsolutePath() returns a string so it cannot be used for a File variable. – Josh Peel Sep 29 '15 at 20:07
  • 1
    `when I add the line creating my file reader, it will no longer compile and run.` File I/O can generate an "Exception". You need to handle the Exception. You can always search the forum for other examples that use a "FileReader", But I suggest you start with the tutorial on [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html). Many methods can generate "Exceptions" so you need to learn how to write a `try/catch` block to handle them. – camickr Sep 29 '15 at 20:13
  • NB You don't need the `.getAbsolutePath()` part. – user207421 Sep 29 '15 at 20:57
  • it didnt work with or without it. however this did fix it public static void main(String[] args) throws FileNotFoundException { – Josh Peel Sep 29 '15 at 22:39

0 Answers0