Web_Sailor 0 Junior Poster

Hi. I am trying to browse a file and use the path variable in my File code. Both the things are in same class. The problem is that I am getting NullPointerException.

Please check if I am doing it correctly

Here the code snippet

I am declaring

public class MyClass extends JFrame {
                public String mypathfile;
  public MyClass() {......}

after my class declaration itself

jButton3.addActionListener(
         new ActionListener() {
           //public String mypathfile;// =  toString();
           public void actionPerformed(ActionEvent e) {
               JFileChooser fileChooser = new JFileChooser(".");
               int status = fileChooser.showOpenDialog(null);

             if (status == JFileChooser.APPROVE_OPTION) {
               File selectedFile = fileChooser.getSelectedFile();
               //System.out.println(selectedFile.getParent());
               //System.out.println(selectedFile.getName());
               //System.out.println(selectedFile.getAbsolutePath());
               mypathfile = selectedFile.getAbsolutePath();
               //System.out.println(mypathfile);
             } else if (status == JFileChooser.CANCEL_OPTION) {
               System.out.println("canceled");
             }
              }
        }
       );

            //File file = new File("inputfile.txt");
             File file = new File(mypathfile);
             System.out.println("The file path is : "+mypathfile);

        try {

            Scanner scan = new Scanner(file);
            if (scan.hasNextLine()) {
                String line = scan.nextLine();
                //System.out.println(line);

............................

         
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.