How are files validated when opened?
Suppose a user selects a file in a dialogue box, and the app then opens the file for reading, etc. Users can open "incorrect" files--they can select a binary file, for example, even if the file they're supposed to be selecting is a text file.
I recognize that sometimes improper file types generate e开发者_JAVA百科xceptions, which can be handled. But sometimes the files don't create exceptions; instead, they just cause the application to work improperly.
What's the standard way to code for these kinds of situations?
- Put a unique identifier into the file (usually the first line or some tag)
- Restrict the file extension
- Do a check on the file whether it's OK
Use 1. if possible or use both 2. and 3.
A lot of operating systems help you out with this by providing filesystem APIs that are at least somewhat file-type-aware (in Cocoa for Mac OS X, there's a setAllowedFileTypes:
method on NSOpenPanel
, for example). Aside from that, you should make sure to define your file format in a way that's easy for you to identify when your program opens a file. A few well-known bytes at the start of your file is probably enough to protect you from most random-file problems.
精彩评论