Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled exception: FileNotFoundException

I have some problems reading file in java: my file is for example:

3,4
2
6
4
1
7
3
8
9

where first line 3 and 4 are the lenght of array A and B and then the element of each array. I made this

import java.io.*;
import java.util.Arrays;

public class Progetto  {

    public static void main(String args[])
      {
// Open the file that is the first 
// command line parameter

            FileInputStream fstream = new FileInputStream("prova.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine = br.readLine(); // step 1

            if (strLine != null) {
              String[] delims = strLine.split(","); // step 2

              // step 3
              int[] a = new int[Integer.parseInt(delims[0])];
              int[] b = new int[Integer.parseInt(delims[1])];

              // step 4
              for (int i=0; i < a.length; i++)
                a[i] = Integer.parseInt(br.readLine());

              // step 5
              for (int i=0; i < b.length; i++)
                b[i] = Integer.parseInt(br.readLine());

              br.close(); // step 6

              // step 7
              System.out.println(Arrays.toString(a));
              System.out.println(Arrays.toString(b));
            }
        }
      }

But it gives me error: -Unhandled exception type FileNotFoundException (line 11) -Unhandled exception type IOException (lines 15 26 30 32) but i don't know why. Someone can help me. Thanks in advance

like image 678
user1841492 Avatar asked Dec 26 '22 22:12

user1841492


1 Answers

Change the way your main method throws IOException. Since these operations may cause either FileNotFoundException or IOException.

    public static void main(String[] args) throws FileNotFoundException {

    }

Or add a try-catch block

   try {
        FileInputStream fstream = new FileInputStream("prova.txt");
        String strLine = br.readLine();
    } catch (IOException e) {
        e.printStackTrace(); 
        // handle exception correctly.
    }

After all these thing make sure that file is exist.

like image 161
Ruchira Gayan Ranaweera Avatar answered Jan 11 '23 19:01

Ruchira Gayan Ranaweera