• Code
  • Tags
  • Users
  • Titles
  • Log in
  • Feedback
  • FAQ
Share Code
Welcome to ForkCan.com

ForkCan is all about sharing code in a social way.

Discuss, debate or argue with other devs about their or your own code.

Give other devs feedback or make a Fork (Make a better version of a shared code).

Rate the code, if you use the code mark it as used so others can see if the shared code is used by someone.

Help each other to be better devs and to be more productive.


Features not working yet:

Flag a post


QR Code

Tiny Url

http://4kcan.com/s/MTk2

Related Code
Detect encoding in InputStream

Detect if file contains XML

Detect whether a File seems to contain XML, taking encoding and whitespace into account

2
462 0 1 0 0 0

With the help of EncodingDetectingInputStream we can make an assumption whether a File is supposed to contain XML or not, without actually parsing the file (for performance reasons). Note that we do NOT make any assumptions of whether the XML is valid.

  public static boolean isXml(File file) {
    FileInputStream fis = null;
    InputStreamReader isr = null;
    try {
      fis = new FileInputStream(file);
      EncodingDetectingInputStream encodingDetectingInputStream = new EncodingDetectingInputStream(fis);

      final Charset charset = encodingDetectingInputStream.getCharset();

      isr = (charset != null) ? // UTF encoding detected by BOM 
        new InputStreamReader(encodingDetectingInputStream, charset) :
        new InputStreamReader(encodingDetectingInputStream);

      char c;

      // Skip leading whitespace
      do {
        c = (char) isr.read();
      } while(c != -1 && Character.isWhitespace(c));

      // If first real character is <, then assume XML. Your case may require reading more characters
      return c == '<';
    }
    catch(IOException ioex) {
      return false; // Probably not an XML file
    }
    finally {
      try {
        if(isr != null)
          isr.close();
        if(fis != null)
          fis.close();
      }
      catch (IOException ioex) {
        // TODO: Handle error
      }
    }

Share: twitter | facebook   Action: used | fork | flag

detect

Mark 'detect' tag as 'like'

Mark 'detect' tag as 'ignore'

file

Mark 'file' tag as 'like'

Mark 'file' tag as 'ignore'

java

Mark 'java' tag as 'like'

Mark 'java' tag as 'ignore'

xml

Mark 'xml' tag as 'like'

Mark 'xml' tag as 'ignore'


 Mattias Jiderhamn
417
July 14, 2010 2:49 PM
edited July 20, 2010 9:46 AM

Fork

 Detect if file contains XML - Mattias Jiderhamn Wednesday 14, 2010 2:49 PM


1 Feedback

Nice and simple solution. Probably the best compromise between accuracy and performance. -  Olivier Friday 16, 2010 9:59 AM

You must log in before you can give any feedback


0 Discussion(s)

Newest Oldest

You must log in before you can post a comment

Squeed
Made by: Fredrik Normén 2010