【问题标题】:Java-Selenium: Eclipse is unable to find my file, but my file is in its working directoryJava-Selenium:Eclipse 无法找到我的文件,但我的文件在其工作目录中
【发布时间】:2015-12-05 05:04:06
【问题描述】:

我正在使用 Eclipse 和 Java 库:java.io.FileInputStream;

我的脚本找不到我想使用构造函数 FileInputStream 分配给变量的文件,即使该文件位于工作目录中。

这是我的代码:

package login.test;
import java.io.File;
import java.io.FileInputStream;
public class QTI_Excelaccess {
        public static void main(String [] args){

        //verify what the working directory is
        String curDir = System.getProperty("user.dir");
        System.out.println("Working Directory is: "+curDir);

        //verify the file is recognized within within the code
         File f = new File("C:\\\\Users\\wes\\workspace\\QTI_crud\\values.xlsx");
            if (f.exists() && !f.isDirectory()){
                System.out.println("Yes, File does exist");
            } else {
                System.out.println("File does not exist");
            }

        //Assign the file to src
        File src = new File("C:\\\\Users\\wes\\workspace\\QTI_crud\\values.xlsx");
        System.out.println("SRC is now: "+src);

        //Get Absolute Path of the File
        System.out.println(src.getAbsolutePath()); 


        FileInputStream fis = new FileInputStream(src);

        }*

我的输出是(当我注释掉最后一行时)是

"工作目录为:C:\Users\wes\workspace\QTI_crud 是的,文件确实存在 SRC 现在是:C:\Users\wes\workspace\QTI_crud\values.xlsx C:\Users\wes\workspace\QTI_crud\values.xlsx"

当我不注释掉最后一行时,我得到了错误:

“线程“主”java.lang.Error 中的异常:未解决的编译问题: 未处理的异常类型 FileNotFoundException

at login.test.QTI_Excelaccess.main(QTI_Excelaccess.java:30)"

我的代码哪里出错了?我对 Java 很陌生

非常感谢!

【问题讨论】:

    标签: java eclipse selenium fileinputstream


    【解决方案1】:

    代码的主要问题是您在知道指定目录中不存在该文件后,您尝试读取该文件。因此,它给了你错误。

    将其重构为这个

    if (f.exists() && !f.isDirectory()){
            System.out.println("Yes, File does exist");
            try {
                FileInputStream fis = new FileInputStream(f);
                //perform operation on the file
                System.out.println(f.getAbsolutePath()); 
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            System.out.println("File does not exist");
        }
    

    如您所见,如果文件存在,则您尝试读取该文件。如果它不可用,你什么都不做。

    【讨论】:

    • 感谢 Jigar,添加 catch-file-exception 有效,脚本现在正在编译。 Java 语法规则需要一些时间来适应,
    • 是的。学习java需要一些时间。几个月内你就会精通java。
    最近更新 更多