Pawan
Pawan

Reputation: 443

Unable to open file from Java file which is in current Directory using Netbeans

I am writing a Java code which reads data from excel sheet and displays content in Jframe. For this I am using apache-poi. This is my code

public static String fileToBeRead="/online.exam/Read.xls";
private void formWindowActivated(java.awt.event.WindowEvent evt) {                                     
    try{
        // TODO add your handling code here:

        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));
        // Refer to the sheet. Put the Name of the sheet to be referred from
        // Alternative you can also refer the sheet by index using getSheetAt(int index)
        HSSFSheet sheet = workbook.getSheet("Sheet1");
        //Reading the TOP LEFT CELL
        HSSFRow row = sheet.getRow(0);
        // Create a cell ate index zero ( Top Left)
        HSSFCell cell = row.getCell(0);
        // Type the content
        System.out.println("THE TOP LEFT CELL--> " + cell.getStringCellValue());            
    }
    catch(IOException ex){
        System.err.println("No such file");
    }

This is the my file pathenter image description here

I am not able to read the file. Please tell me how to rectify the problem.

Upvotes: 0

Views: 464

Answers (2)

monty
monty

Reputation: 8775

I don't use Netbeans but according I think in some cases it shows the same behaviour as Eclipse.

try

public static String fileToBeRead="src/online/exam/Read.xls";

why:

  • /online.exam/Read.xls would translate into C:\online.exam\Read.xls. Leaving the first slash makes the path relativ to the working directory (your Online.Exam root directory on the screenshot)
  • src because I guess Netbeans also seperates source and binary in sub directories. A better approach may is putting the Read.xls into a directory "data" on the same level as Libraries and Source Packages (then the path would be data/Read.xls).
  • online/exam instead of online.exam because online exam is the package name which splits up into 2 directories

Upvotes: 1

centic
centic

Reputation: 15890

I think you mix up Netbeans project structure and actual physical file layout.

The path /online.exam/Read.xls seems to be the Netbeans way of stating that there is a project online.exam which contains a file Read.xls.

However the Java code does not know about the Netbeans project structure, so it is not able to find the file at this location.

You can try either of the following:

  • Use a relative path, IDEs usually start the application in the root folder of the project, so a path of simply Read.xls (without any slash) may work here

  • Use an absolute path. For this you would need to find out where in the filesystem the file is located and specify this path, i.e. the same as you would specify if you open the file in Microsoft Excel or LibreOffice.

Upvotes: 1

Related Questions