开发者

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 = 开发者_JAVA技巧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");
    }
}


You could cover the most by sniffing the mime type based on the file extension or, even better, the actual file content. You can do that with help of among others jMimeMagic (Maven coords here). If the mime type does not start with "text", then it's certainly not a text file.

String mimeType = Magic.getMagicMatch(file, false).getMimeType();
boolean text = mimeType.startsWith("text");


I found that MIME types can really help with this! JAF


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;
}
/*...*/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜