简体   繁体   中英

cannot find file for createNewFile

I'm writing a private method in Java that reads and write to a simple text file, which it should make if it doesn't exist since createNewFile() checks for that first.

private boolean updateGameQuota(String name, String quantity) {
    ...
    File quotaLog = new File("seller-quotas.txt");
    quotaLog.createNewFile();
    ...
    return ret;
}

The compile-time error is: SmsFunctions.java:256: error: unreported exception IOException; must be caught or declared to be thrown quotaLog.createNewFile(); ^ 1 error

Placing it in a try-catch block doesn't seem to be the issue, as I tried that (also on many other lines that try passing quotaLog) but eventually I get to a point where it's clear that something else is wrong. The File object is fine, but then if I try to use createNewFile or say

FileReader sQReader = new FileReader(quotaLog);

I get a FileNotFoundException even though the file is definitely there and I tried this on other text files which are read elsewhere successfully with the same result.

Any help or ideas would be greatly appreciated!

Update : So in the end my issue was indeed just putting try-catch blocks around everything and making sure variables set within them were first created outside of those blocks. My confusion came from a false sense of sureness that fileraders/filewriters shoulnd't need try catch blocks (I could swear I've used them without many times) and the error was actually an indication of something else. Perhaps before closing the thread someone could elaborate as to why Java doesn't always make a fuss about it, if that's true?

Thanks!

File.createNewFile() can throw an IOException (a checked exception) and needs to be surrounded in a try-catch block or the method you're using it in needs to be declared as throws IOException and you need to handle it upstream.

To debug the FileNotFoundException, you could try:

File quotaLog = new File("seller-quotas.txt");
System.out.println(quotaLog.getAbsolutePath());

Which uses the File.getAbsolutePath() method to print where it expects the file to exist.

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