简体   繁体   中英

Getting error saying file won't open in Java...any idea why this is happening?

I think I am really close, but I am unable to open a file I have called LocalNews.txt. Error says can't find file specified.

    String y = "LocalNews.txt";
FileInputStream fstream = new FileInputStream(y);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

Name of file is LocalNews.txt in library called News....anyone know why the file will not open?

The file is in the same Java Project that I am working on.

Error: LocalNews.txt (The system cannot find the file specified)

Project is named Bst, package is src in subPackage newsFinder, and library that the text files are stored in is called News.

Found out it was looking in

C:\EclipseIndigoWorkspace1\Bst\bin\LocalNews.txt

But I want it to look in (I believe)

C:\EclipseIndigoWorkspace1\Bst\News\LocalNews.txt

But if I make the above url a string, I get an error.

String y = "LocalNews.txt";

instead use

String y = "path from root/LocalNews.txt"; //I mean the complete path of the file

Your program can probably not find the file because it is looking in another folder.

Try using a absolute path like

String y = "c:\\temp\\LocalNews.txt";

By 'library called News' I assume you mean a jar file like News.jar which is on the classpath and contains the LocalNews.txt file you need. If this is the case, then you can get an InputStream for it by calling:

InputStream is = Thread.currentThread().getContextClassLoader()
    .getResourceAsStream("LocalNews.txt");

Use

    System.out.println(System.getProperty("user.dir") );

to find out what your current directory is. Then you'll know for sure whether your file is in the current directory or not. If it is not, then you have to specify the path so that it looks in the right directory.

Also, try this -

     File file = new File (y);
     System.out.println(file.getCanonicalPath());

This will tell you the exact path of your file on the system, provided your file is in the current directory. If it does not, then you know your file is not in the current directory.

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