2 * Meviz - Various tools collection to work with multimedia. Author: Svjatoslav Agejenko.
3 * This project is released under Creative Commons Zero (CC0) license.
7 package eu.svjatoslav.meviz.bomremove;
9 import eu.svjatoslav.commons.file.IOHelper;
10 import eu.svjatoslav.commons.string.GlobMatcher;
11 import eu.svjatoslav.meviz.Module;
14 import java.io.FileInputStream;
15 import java.io.IOException;
16 import java.util.Arrays;
18 public class Main implements Module {
20 private final byte[] bomHeader = new byte[]{(byte) 0xef, (byte) 0xbb, (byte) 0xbf};
22 private final CommandlineHandler commandlineHandler = new CommandlineHandler();
24 private BomStrippingOptions options;
26 private boolean contains(final byte[] header, final byte[] patternToSeek) {
28 for (int i = 0; i < patternToSeek.length; i++)
29 if (header[i] != patternToSeek[i])
35 private boolean fileContainsHeader(final File file)
38 final FileInputStream fileInputStream = new FileInputStream(file);
40 final byte[] currentFileHeader = new byte[bomHeader.length];
41 fileInputStream.read(currentFileHeader);
42 fileInputStream.close();
44 return contains(currentFileHeader, bomHeader);
47 private boolean fileMatchesInputPattern(final File file) {
48 final String fileName = file.getName().toLowerCase();
50 for (final String inputPattern : options.inputPatterns)
51 if (GlobMatcher.match(fileName, inputPattern.toLowerCase()))
58 public String getDescription() {
59 return "Remove byte order mark (bom) from UTF text files if they are present.";
63 public String getModuleCommand() {
67 private void processDirectory(final File directory) {
69 for (final File subFile : directory.listFiles())
70 if (subFile.isDirectory()) {
71 if (options.recursive)
72 processDirectory(subFile);
73 } else if (fileMatchesInputPattern(subFile))
76 } catch (final IOException exception) {
77 System.out.println("Error processing file: "
78 + subFile.getAbsolutePath());
79 System.out.println(" exception: "
80 + exception.getMessage());
85 private void processFile(final File file) throws IOException {
87 if (file.length() < bomHeader.length)
90 if (!fileContainsHeader(file))
93 System.out.println("Removing BOM from: " + file.getAbsolutePath());
94 stripFileFromHeader(file);
98 public void run(final String[] args) throws IOException {
100 options = commandlineHandler.parseCommandlineArguments(args);
102 if (options == null) {
103 showCommandlineHelp();
107 processDirectory(options.targetDirectory);
112 public void showCommandlineHelp() {
113 commandlineHandler.parser.showHelp();
116 private void stripFileFromHeader(final File file)
119 final byte[] fileContents = IOHelper.getFileContents(file);
121 // remove BOM header form file
122 final byte[] newFileContents = Arrays.copyOfRange(fileContents,
123 bomHeader.length, fileContents.length);
125 // overwrite file with new contents
126 IOHelper.saveToFile(file, newFileContents);