无法使用Netbeans从当前目录中的Java文件打开文件
我正在编写一个Java代码,它从excel工作表中读取数据,并在Jframe中显示内容。为此,我使用ApachePOI。这是我的密码无法使用Netbeans从当前目录中的Java文件打开文件,java,netbeans,apache-poi,Java,Netbeans,Apache Poi,我正在编写一个Java代码,它从excel工作表中读取数据,并在Jframe中显示内容。为此,我使用ApachePOI。这是我的密码 public static String fileToBeRead="/online.exam/Read.xls"; private void formWindowActivated(java.awt.event.WindowEvent evt) { try{ //
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");
}
这是我的文件路径
我看不懂这个文件。请告诉我如何纠正这个问题。我认为您混淆了Netbeans项目结构和实际的物理文件布局 路径
/online.exam/Read.xls
似乎是Netbeans声明有一个项目online.exam
,其中包含一个文件Read.xls
但是,Java代码不知道Netbeans项目结构,因此无法在此位置找到文件
您可以尝试以下任一方法:
- 如果使用相对路径,IDE通常会在项目的根文件夹中启动应用程序,因此这里可以使用简单的
(不带斜杠)路径Read.xls
- 使用绝对路径。为此,您需要找出文件在文件系统中的位置并指定此路径,即与在Microsoft Excel或LibreOffice中打开文件时指定的路径相同
- /online.exam/Read.xls将转换为C:\online.exam\Read.xls。保留第一个斜杠使路径相对于工作目录(屏幕截图上的Online.Exam根目录)
- src,因为我猜Netbeans也在子目录中分离源代码和二进制代码。更好的方法可能是将Read.xls放入与库和源程序包处于同一级别的目录“data”(那么路径将是data/Read.xls)李>
- online/exam而不是online.exam,因为online exam是分为2个目录的包名
- 我不使用Netbeans,但据我所知,在某些情况下,它显示出与Eclipse相同的行为
试一试
原因:
public static String fileToBeRead="src/online/exam/Read.xls";