Question

I am creating a file on a network drive and then adding data to it. Time to time writing to that file fails. Is there a good way of checking if the file is accessible before every time i save data to it or maybe is tehre a way checking afther to see if the data was saved?

EDIT: Right now i am using try-catch block with PrintStream in my code:

        try
        {
            logfile = new File(new File(isic_log), "log_" + production);
            //nasty workaround - we'll have a file the moment we assign an output stream to it
            if (!logfile.exists())
            {
                    prodrow = production;
            }

            out = new FileOutputStream(logfile.getPath(), logfile.exists());
            p = new PrintStream(out);
            if (prodrow != "")
            {
                p.println (prodrow);
            }
            p.println (chip_code + ":" + isic_number);
            p.close();
        }
        catch (Exception e)
        {
                logger.info("Got exception while writing to isic production log: " + e.getMessage());
        }

So might be the PrintStream the problem? (PrintWriter and PrintStream never throw IOExceptions)

Was it helpful?

Solution

I would use plain BufferedWriter and add the newlines myself as required.


Normal FileOutputStream operations should throw an IOException if there is an error.

AFAIK, The only exception is PrintWriter which does not throw an exception. Instead you need to call checkError() but it gives you no indication of what the error was or when it occurred.

I suggest you not use PrintWriter in this situation.

OTHER TIPS

The only reasonable way to address this is to try to write to the file, and handle any resulting exception in an appropriate manner. It's pretty much impossible to know beforehand whether an I/O operation is going to succeed, due to the unreliable nature of networks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top