svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.library / org.gvsig.expressionevaluator / org.gvsig.expressionevaluator.lib / org.gvsig.expressionevaluator.lib.impl / src / main / java / org / gvsig / expressionevaluator / impl / EncodingUtils.java @ 46517
History | View | Annotate | Download (1.79 KB)
1 |
package org.gvsig.expressionevaluator.impl; |
---|---|
2 |
|
3 |
import java.io.BufferedReader; |
4 |
import java.io.File; |
5 |
import java.io.FileInputStream; |
6 |
import java.io.IOException; |
7 |
import java.io.InputStream; |
8 |
import java.io.InputStreamReader; |
9 |
import java.util.regex.Matcher; |
10 |
import java.util.regex.Pattern; |
11 |
import org.apache.commons.lang3.StringUtils; |
12 |
|
13 |
/**
|
14 |
*
|
15 |
* @author jjdelcerro
|
16 |
*/
|
17 |
public class EncodingUtils { |
18 |
|
19 |
private static final Pattern RE_ENCODING = Pattern.compile(".*encoding[:]\\s*\"?([a-zA-Z_][a-zA-Z0-9_-]*)\"?.*"); |
20 |
|
21 |
public static String getEncoding(File f) { |
22 |
String line = getFirstLine(f);
|
23 |
String encoding = getEncoding(line);
|
24 |
return encoding;
|
25 |
} |
26 |
|
27 |
public static String getEncoding(InputStream is) { |
28 |
String line = getFirstLine(is);
|
29 |
String encoding = getEncoding(line);
|
30 |
return encoding;
|
31 |
} |
32 |
|
33 |
public static String getEncoding(String line) { |
34 |
if( StringUtils.isBlank(line) ) {
|
35 |
return null; |
36 |
} |
37 |
String encoding = null; |
38 |
Matcher m = RE_ENCODING.matcher(line);
|
39 |
if (m != null && m.matches() && m.groupCount() == 1) { |
40 |
String s = m.group(1); |
41 |
if (!StringUtils.isBlank(s)) {
|
42 |
encoding = s; |
43 |
} |
44 |
} |
45 |
return encoding;
|
46 |
} |
47 |
|
48 |
public static String getFirstLine(File f) { |
49 |
String line;
|
50 |
try (FileInputStream is = new FileInputStream(f)) { |
51 |
line = getFirstLine(is); |
52 |
} catch (Exception ex) { |
53 |
return null; |
54 |
} |
55 |
return line;
|
56 |
} |
57 |
|
58 |
public static String getFirstLine(InputStream is) { |
59 |
String line;
|
60 |
try (InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) { |
61 |
line = br.readLine(); |
62 |
while (line != null) { |
63 |
if (!StringUtils.isBlank(line)) {
|
64 |
break;
|
65 |
} |
66 |
line = br.readLine(); |
67 |
} |
68 |
} catch (IOException ex) { |
69 |
return null; |
70 |
} |
71 |
return line;
|
72 |
} |
73 |
} |