Advertisement
nazar_art

EncodindsCheck

Mar 7th, 2013
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. class EncodindsCheck implements Checker {
  2.     private static final int UTF8_HEADER_SIZE = 8;
  3.  
  4.     @Override
  5.     public boolean check(File currentFile) {
  6.         if (isUTF8(currentFile)) {
  7.             return true;
  8.         } else {
  9.             return false;
  10.         }
  11.     }
  12.  
  13.     public static boolean isUTF8(File file) {
  14.         // validate input
  15.         if (null == file) {
  16.             throw new IllegalArgumentException("input file can't be null");
  17.         }
  18.         if (file.isDirectory()) {
  19.             throw new IllegalArgumentException(
  20.                     "input file refers to a directory");
  21.         }
  22.  
  23.         // read input file
  24.         byte[] buffer;
  25.         try {
  26.             buffer = readUTFHeaderBytes(file);
  27.         } catch (IOException e) {
  28.             throw new IllegalArgumentException(
  29.                     "Can't read input file, error = " + e.getLocalizedMessage());
  30.         }
  31.  
  32.         if ((buffer[0] & 0xF8) == 0xF0) {
  33.             if (((buffer[1] & 0xC0) == 0x80)
  34.                     && ((buffer[2] == 0x80) && ((buffer[3] == 0x80))))
  35.                 return true;
  36.         } else if ((buffer[0] & 0xF0) == 0xE0) {
  37.             if (((buffer[1] & 0xC0) == 0x80) && ((buffer[2] & 0xC0) == 0x80))
  38.                 return true;
  39.         } else if ((buffer[0] & 0xE0) == 0xC0) {
  40.             if (((buffer[1] & 0xC0) == 0x80))
  41.                 return true;
  42.         }
  43.  
  44.         return false;
  45.     }
  46.  
  47.     private static byte[] readUTFHeaderBytes(File input) throws IOException {
  48.         byte[] buffer = new byte[UTF8_HEADER_SIZE];
  49.         // read data
  50.         FileInputStream fis = new FileInputStream(input);
  51.         fis.read(buffer);
  52.         fis.close();
  53.         return buffer;
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement