Java tutorial
/* * Copyright 2015 Patrik Karlsson. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.trixon.toolbox.alphatrans.cmd; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.openide.modules.InstalledFileLocator; import org.openide.util.Exceptions; import se.trixon.almond.Xlog; import se.trixon.toolbox.alphatrans.AlphatransController; /** * * @author Patrik Karlsson <patrik@trixon.se> */ public class CmdIconv { private String mCommand = "iconv"; public CmdIconv() { if (SystemUtils.IS_OS_WINDOWS) { File file = InstalledFileLocator.getDefault().locate("iconv.exe", "se.trixon.toolbox.alphatrans.windows", false); mCommand = file.getAbsolutePath(); } } public String convert(File source, File dest, String fromCharset, String toCharset, boolean omit) { String result = null; ArrayList<String> cmdElements = new ArrayList<>(); cmdElements.add(mCommand); cmdElements.add("-f"); cmdElements.add(fromCharset); cmdElements.add("-t"); cmdElements.add(toCharset); if (omit) { cmdElements.add("-c"); } cmdElements.add(source.getAbsolutePath()); String[] cmd = cmdElements.toArray(new String[cmdElements.size()]); Xlog.v(AlphatransController.LOG_TAG, StringUtils.join(cmd, " ")); ProcessBuilder processBuilder = new ProcessBuilder(cmd); processBuilder.redirectOutput(dest); try { Process process = processBuilder.start(); process.waitFor(); result = IOUtils.toString(process.getErrorStream()); if (result.length() == 0) { result = null; } } catch (IOException | InterruptedException ex) { Exceptions.printStackTrace(ex); } return result; } public String[] list() { String[] charSets = { "" }; String[] cmd = { mCommand, "-l" }; try { Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); charSets = IOUtils.toString(p.getInputStream()).split("\\s+"); for (int i = 0; i < charSets.length; i++) { charSets[i] = charSets[i].replace("/", ""); } } catch (IOException | InterruptedException ex) { Exceptions.printStackTrace(ex); } Arrays.sort(charSets); return charSets; } }