Example usage for org.apache.commons.io FileUtils openOutputStream

List of usage examples for org.apache.commons.io FileUtils openOutputStream

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils openOutputStream.

Prototype

public static FileOutputStream openOutputStream(File file) throws IOException 

Source Link

Document

Opens a FileOutputStream for the specified file, checking and creating the parent directory if it does not exist.

Usage

From source file:com.turn.ttorrent.client.main.TorrentMain.java

/**
 * Torrent creator.//from w w w . j ava2  s  . c om
 *
 * <p>
 * You can use the {@code main()} function of this class to create
 * torrent files. See usage for details.
 * </p>
 */
public static void main(String[] args) throws Exception {
    // BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n")));

    OptionParser parser = new OptionParser();
    OptionSpec<Void> helpOption = parser.accepts("help").forHelp();
    OptionSpec<File> inputOption = parser.accepts("input").withRequiredArg().ofType(File.class).required()
            .describedAs("The input file or directory for the torrent.");
    OptionSpec<File> outputOption = parser.accepts("output").withRequiredArg().ofType(File.class).required()
            .describedAs("The output torrent file.");
    OptionSpec<URI> announceOption = parser.accepts("announce").withRequiredArg().ofType(URI.class).required()
            .describedAs("The announce URL for the torrent.");
    parser.nonOptions().ofType(File.class).describedAs("Files to include in the torrent.");

    OptionSet options = parser.parse(args);
    List<?> otherArgs = options.nonOptionArguments();

    // Display help and exit if requested
    if (options.has(helpOption)) {
        System.out.println("Usage: Torrent [<options>] <torrent-file>");
        parser.printHelpOn(System.err);
        System.exit(0);
    }

    List<File> files = new ArrayList<File>();
    for (Object o : otherArgs)
        files.add((File) o);
    Collections.sort(files);

    TorrentCreator creator = new TorrentCreator(options.valueOf(inputOption));
    if (!files.isEmpty())
        creator.setFiles(files);
    creator.setAnnounceList(options.valuesOf(announceOption));
    Torrent torrent = creator.create();

    File file = options.valueOf(outputOption);
    OutputStream fos = FileUtils.openOutputStream(file);
    try {
        torrent.save(fos);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.textocat.textokit.postagger.GenerateAggregateDescriptorForMorphAnnotator.java

public static void main(String[] args) throws UIMAException, IOException, SAXException {
    if (args.length != 1) {
        System.err.println("Usage: <output-path>");
        System.exit(1);// ww  w .j a v a 2 s  .  c  o m
    }
    String outputPath = args[0];
    // NOTE! A file URL for generated SerializedDictionaryResource description assumes
    // that the required dictionary file is within one of UIMA datapath folders.
    // So users of the generated aggregate descriptor should setup 'uima.datapath' properly .
    ExternalResourceDescription morphDictDesc = getMorphDictionaryAPI()
            .getResourceDescriptionWithPredictorEnabled();

    Map<String, MetaDataObject> aeDescriptions = Maps.newLinkedHashMap();
    aeDescriptions.put("tokenizer", TokenizerAPI.getAEImport());
    //
    aeDescriptions.put("sentence-splitter", SentenceSplitterAPI.getAEImport());
    //
    aeDescriptions.put("morph-analyzer", MorphologyAnnotator.createDescription(DefaultAnnotationAdapter.class,
            PosTaggerAPI.getTypeSystemDescription()));
    //
    aeDescriptions.put("tag-assembler", TagAssembler.createDescription());
    AnalysisEngineDescription desc = PipelineDescriptorUtils.createAggregateDescription(aeDescriptions);
    // bind the dictionary resource
    bindExternalResource(desc, "morph-analyzer/" + MorphologyAnnotator.RESOURCE_KEY_DICTIONARY, morphDictDesc);
    bindExternalResource(desc, "tag-assembler/" + GramModelBasedTagMapper.RESOURCE_GRAM_MODEL, morphDictDesc);

    FileOutputStream out = FileUtils.openOutputStream(new File(outputPath));
    try {
        desc.toXML(out);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:edu.cornell.med.icb.goby.reads.ColorSpaceConverter.java

public static void main(final String[] args) throws JSAPException, IOException {
    final JSAP jsap = new JSAP();

    final FlaggedOption sequenceOption = new FlaggedOption("input");
    sequenceOption.setRequired(true);/*from   w  ww. j av a  2 s  .  com*/
    sequenceOption.setLongFlag("input");
    sequenceOption.setShortFlag('i');
    sequenceOption.setStringParser(FileStringParser.getParser().setMustBeFile(true).setMustExist(true));
    sequenceOption.setHelp("The input file (in Fasta format) to convert");
    jsap.registerParameter(sequenceOption);

    final FlaggedOption outputOption = new FlaggedOption("output");
    outputOption.setRequired(false);
    outputOption.setLongFlag("output");
    outputOption.setShortFlag('o');
    outputOption.setStringParser(FileStringParser.getParser().setMustBeFile(true));
    outputOption.setHelp("The output file to write to (default = stdout)");
    jsap.registerParameter(outputOption);

    final FlaggedOption titleOption = new FlaggedOption("title");
    titleOption.setRequired(false);
    titleOption.setLongFlag("title");
    titleOption.setShortFlag('t');
    titleOption.setHelp("Title for this conversion");
    jsap.registerParameter(titleOption);

    final Switch verboseOption = new Switch("verbose");
    verboseOption.setLongFlag("verbose");
    verboseOption.setShortFlag('v');
    verboseOption.setHelp("Verbose output");
    jsap.registerParameter(verboseOption);

    final Switch helpOption = new Switch("help");
    helpOption.setLongFlag("help");
    helpOption.setShortFlag('h');
    helpOption.setHelp("Print this message");
    jsap.registerParameter(helpOption);

    jsap.setUsage("Usage: " + ColorSpaceConverter.class.getName() + " " + jsap.getUsage());

    final JSAPResult result = jsap.parse(args);

    if (result.getBoolean("help")) {
        System.out.println(jsap.getHelp());
        System.exit(0);
    }

    if (!result.success()) {
        final Iterator<String> errors = result.getErrorMessageIterator();
        while (errors.hasNext()) {
            System.err.println(errors.next());
        }
        System.err.println(jsap.getUsage());
        System.exit(1);
    }

    final boolean verbose = result.getBoolean("verbose");

    final File sequenceFile = result.getFile("input");
    if (verbose) {
        System.out.println("Reading sequence from: " + sequenceFile);
    }

    // extract the title to use for the output header
    final String title;
    if (result.contains("title")) {
        title = result.getString("title");
    } else {
        title = sequenceFile.getName();
    }

    Reader inputReader = null;
    PrintWriter outputWriter = null;

    try {
        if ("gz".equals(FilenameUtils.getExtension(sequenceFile.getName()))) {
            inputReader = new InputStreamReader(new GZIPInputStream(FileUtils.openInputStream(sequenceFile)));
        } else {
            inputReader = new FileReader(sequenceFile);
        }
        final FastaParser fastaParser = new FastaParser(inputReader);

        final File outputFile = result.getFile("output");
        final OutputStream outputStream;
        if (outputFile != null) {
            outputStream = FileUtils.openOutputStream(outputFile);
            if (verbose) {
                System.out.println("Writing sequence : " + outputFile);
            }
        } else {
            outputStream = System.out;
        }
        outputWriter = new PrintWriter(outputStream);

        // write the header portion of the output
        outputWriter.print("# ");
        outputWriter.print(new Date());
        outputWriter.print(' ');
        outputWriter.print(ColorSpaceConverter.class.getName());
        for (final String arg : args) {
            outputWriter.print(' ');
            outputWriter.print(arg);
        }
        outputWriter.println();
        outputWriter.print("# Cwd: ");
        outputWriter.println(new File(".").getCanonicalPath());
        outputWriter.print("# Title: ");
        outputWriter.println(title);

        // now parse the input sequence
        long sequenceCount = 0;
        final MutableString descriptionLine = new MutableString();
        final MutableString sequence = new MutableString();
        final MutableString colorSpaceSequence = new MutableString();

        while (fastaParser.hasNext()) {
            fastaParser.next(descriptionLine, sequence);
            outputWriter.print('>');
            outputWriter.println(descriptionLine);

            convert(sequence, colorSpaceSequence);
            CompactToFastaMode.writeSequence(outputWriter, colorSpaceSequence);

            sequenceCount++;
            if (verbose && sequenceCount % 10000 == 0) {
                System.out.println("Converted " + sequenceCount + " entries");
            }
        }

        if (verbose) {
            System.out.println("Conversion complete!");
        }
    } finally {
        IOUtils.closeQuietly(inputReader);
        IOUtils.closeQuietly(outputWriter);
    }
}

From source file:com.buddycloud.mediaserver.business.util.ImageUtils.java

public static File storeImageIntoFile(BufferedImage image, String imageFormat, String pathToStore)
        throws IOException {

    // Store into provided path
    File output = new File(pathToStore);
    ImageIO.write(image, imageFormat, FileUtils.openOutputStream(output));

    return output;
}

From source file:birdnest.client.deamon.Settings.java

public void saveSettings() {
    try {/*from w  w  w . j  a  v  a2s.  c o m*/
        this.store(FileUtils.openOutputStream(currentFile), "Birdnest Client Deamon Settings");
    } catch (IOException ex) {
        Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.thenairn.linker.config.Libraries.java

/**
 * Puts library to temp dir and loads to memory
 *//*from w  w  w.  j ava  2 s . c o  m*/
private static void loadLib(String path, String name) {
    name = name + ".dll";
    try {
        // have to use a stream
        InputStream in = Libraries.class.getResourceAsStream(LIB_BIN + name);
        // always write to different location
        File fileOut = new File(System.getProperty("java.io.tmpdir") + "/" + path + LIB_BIN + name);
        logger.info("Writing dll to: " + fileOut.getAbsolutePath());
        OutputStream out = FileUtils.openOutputStream(fileOut);
        IOUtils.copy(in, out);
        in.close();
        out.close();
        System.load(fileOut.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.dv.util.DataViewerZipUtil.java

/**
 * ?.//from   ww  w .ja  v  a 2  s .  c o m
 * ?, .
 * @param srcFile ?
 * @param destFile ?
 * @throws IOException
 */
public static void zipFile(File srcFile, File destFile) throws IOException {
    zipFile(srcFile, FileUtils.openOutputStream(destFile));
}

From source file:com.sap.prd.mobile.ios.mios.ScriptRunner.java

private static File copyScript(String script, File workingDirectory) throws IOException {
    if (!workingDirectory.exists())
        if (!workingDirectory.mkdirs())
            throw new IOException("Cannot create directory '" + workingDirectory + "'.");

    final File scriptFile = new File(workingDirectory, getScriptFileName(script));
    scriptFile.deleteOnExit();//  w ww. j  a  v a  2s  . c o  m

    OutputStream os = null;
    InputStream is = null;

    try {
        is = ScriptRunner.class.getResourceAsStream(script);

        if (is == null)
            throw new FileNotFoundException(script + " not found.");

        os = FileUtils.openOutputStream(scriptFile);

        IOUtils.copy(is, os);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

    Forker.forkProcess(System.out, null, "chmod", "755", scriptFile.getCanonicalPath());
    return scriptFile;
}

From source file:com.enderville.enderinstaller.util.InstallScript.java

/**
 * Repackages all the files in the tmp directory to the new minecraft.jar
 *
 * @param tmp The temp directory where mods were installed.
 * @param mcjar The location to save the new minecraft.jar.
 * @throws IOException/*from w  w w . ja va 2s  .c  o  m*/
 */
public static void repackMCJar(File tmp, File mcjar) throws IOException {
    byte[] dat = new byte[4 * 1024];

    JarOutputStream jarout = new JarOutputStream(FileUtils.openOutputStream(mcjar));

    Queue<File> queue = new LinkedList<File>();
    for (File f : tmp.listFiles()) {
        queue.add(f);
    }

    while (!queue.isEmpty()) {
        File f = queue.poll();
        if (f.isDirectory()) {
            for (File child : f.listFiles()) {
                queue.add(child);
            }
        } else {
            //TODO need a better way to do this
            String name = f.getPath().substring(tmp.getPath().length() + 1);
            //TODO is this formatting really required for jars?
            name = name.replace("\\", "/");
            if (f.isDirectory() && !name.endsWith("/")) {
                name = name + "/";
            }
            JarEntry entry = new JarEntry(name);
            jarout.putNextEntry(entry);

            FileInputStream in = new FileInputStream(f);
            int len = -1;
            while ((len = in.read(dat)) > 0) {
                jarout.write(dat, 0, len);
            }
            in.close();
        }
        jarout.closeEntry();
    }
    jarout.close();

}

From source file:com.ewcms.content.resource.service.operator.FileOperator.java

@Override
public String write(InputStream source, UriRuleable uriRule, String suffix) throws IOException {

    try {/*from  w  w w  . j ava 2s  .  c o m*/
        String uri = uriRule.getUri();
        if (suffix != null && !suffix.equals("")) {
            uri = uri + "." + suffix;
        }
        OutputStream target = FileUtils.openOutputStream(getLocalFile(uri));
        byte[] buff = new byte[1024 * 10];
        while (source.read(buff) > 0) {
            target.write(buff);
        }
        target.flush();
        target.close();
        source.close();

        return uri;
    } catch (PublishException e) {
        logger.error("Resource uri is error :{}", e);
        throw new IOException(e);
    }
}