简体   繁体   中英

Unable to find the file kept inside project

I have an excel file which I have kept in a subfolder of my main package. I want to read that file. When I read it using InputStream , it file is easily detected but when I read using FileInputStram or File file = new File(filepath) I get the error that the file is not found.

Can anyone help me in reading the file using FileInputStram or File file = new File(filepath) ?

The code what I wrote to read the file is

File file = new File("upgradeworkbench/Resources/workbookOut.xlsm");

and

FileInputStream inp = new FileInputStream("upgradeworkbench/Resources/workbookOut.xlsm");

I tried with / in the beginning of the path but still it didn't work.

When working with File class you need to provide either absolute or relative path. Absolute path is the full file path eg C:\\workbookOut.xlsm

In relative paths, there is a concept of a working directory and it's represented by a . (dot) and everything else is relative to it.

Try either giving the full path or the relative path.

File file = new File("./upgradeworkbench/Resources/workbookOut.xlsm");

If your file in classpath then try below code

package mypack;

import java.io.*;

public class TestPath
{

    public static void main(String[] args) throws Exception
    {
        InputStream stream = Test.class.getResourceAsStream("/workbookOut.xlsm");
        System.out.println(stream != null);
        stream = Test.class.getClassLoader()
            .getResourceAsStream("workbookOut.xlsm");
        System.out.println(stream != null);
    }
}

If your file in same package then use the below line it will work

URL url = getClass().getResource("workbookOut.xlsm");

File file =new File(url.getPath());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM