Hridayam Bakshi
Hridayam Bakshi

Reputation: 74

java.io.FileNotFoundException when reading .csv file

I'm supposed to create a java applet project and in that I need to read data from .csv file and put it in a scrollable table. I tried to dothat and i get a FileNotFoundException exception.

Here is my code:

import java.applet.Applet;
import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

@SuppressWarnings("serial")
public class Test extends Applet
{  
   Table table;
   public void init()
   {
      try
      {
         table = new Table();
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
      this.add(table);
   }
}



class Table extends JPanel
{
   private String[][] productList;
   private JTable table;

   public Table() throws Exception
   {
      read();
      BorderLayout layout = new BorderLayout();
      layout.addLayoutComponent(new JScrollPane(table), BorderLayout.CENTER);

      setLayout(layout);
   }

   private void read() throws Exception
   {
      ArrayList<String[]> list = new ArrayList<String[]>();
      try
      {
         BufferedReader br = new BufferedReader(new FileReader("Products.csv"));
         String line = br.readLine();

         while ((line = br.readLine()) != null)
         {
            String[] toBeAdded = line.split(",");
            list.add(toBeAdded);
         }
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }

      productList = new String[list.size()][3];
      for (int i = 0; i < productList.length; i++)
         for (int j = 0; j < productList[i].length; j++)
            productList[i][j] = list.get(i)[j];
   }
}

The products.csv is there in the root folder. I try to read in a normal non swing project and it works but not for this. Can anyone help me?

Upvotes: 0

Views: 2020

Answers (1)

Powerlord
Powerlord

Reputation: 88796

I can think of two potential problems:

  1. An applet can't read files located on the web server.
  2. If the file is packed inside a jar file, you need special code in order to read it. Specifically, you need a ClassLoader's getResourceAsStream.

For the second, the easiest way to get the ClassLoader's getResourceAsStream is to call Class's getResourceAsStream.

I haven't tested it, but something like this should work:

BufferedReader br = new BufferedReader(new InputStreamReader(Table.class.getResourceAsStream("/Products.csv")));

If that doesn't compile, change Table.class to this.getClass()

Note that the / is there to indicate that Products.csv is at the root of the .jar file. Otherwise, it will use the package name as a directory to look in (i.e. if the package was package this.is.my.boomstick;, it'd try to open this/is/my/boomstick/Products.csv)

Upvotes: 1

Related Questions