Skip to content
Advertisement

Java InputReader. Detect if file being read is binary?

I had posted a question in regards to this code. I found that JTextArea does not support the binary type data that is loaded.

So my new question is how can I go about detecting the ‘bad’ file and canceling the file I/O and telling the user that they need to select a new file?

class Open extends SwingWorker<Void, String>
{
    File file;
    JTextArea jta;

    Open(File file, JTextArea jta)
    {
        this.file = file;
        this.jta = jta;
    }

    @Override
    protected Void doInBackground() throws Exception
    {
        BufferedReader br = null;

        try
        {
            br = new BufferedReader(new FileReader(file));

            String line = br.readLine();

            while(line != null)
            {
                publish(line);
                line = br.readLine();
            }
        }
        finally
        {
            try
            {
                br.close();
            } catch (IOException e) { }
        }
        return null;
    }

    @Override
    protected void process(List<String> chunks)
    {
        for(String s : chunks)
            jta.append(s + "n");
    }
}

Advertisement

Answer

For those who read this and are curious as to what I have done to fix the File reading problem…. I have instead implemented a FileReader and have experienced no problems on Windows. I have however noticed on Linux that there are some problems which tends to lead to a crash. Also I noticed when running through an IDE such as Netbeans I receive various runtime errors when trying to load a binary file and massive slow-down; but when I execute the .jar as an executable and not from the IDE it works fine.

Here is relevant code that I have had no problem with (even when loading binary file types such as .mp3, .exe, etc.)

/*...*/
@Override
protected Void doInBackground() throws Exception {
    BufferedReader br = null;

    try {
        br = new BufferedReader(new FileReader(file));
        int ch = br.read();

        while(ch != -1) {
            publish(ch);
            ch = br.read();
        }
    }
    finally {
        try {
            br.close();
        } catch (IOException e) {}
    }
    System.gc();
    return null;
}
/*...*/
Advertisement