Example usage for java.io IOException IOException

List of usage examples for java.io IOException IOException

Introduction

In this page you can find the example usage for java.io IOException IOException.

Prototype

public IOException(Throwable cause) 

Source Link

Document

Constructs an IOException with the specified cause and a detail message of (cause==null ?

Usage

From source file:Main.java

/**
 * Writes an xml representation to a stream.
 *
 * @param doc// w w  w.j a v a  2  s.  c o m
 *          the document
 * @param out
 *          the output stream
 * @throws IOException
 *           if there is an error transforming the dom to a stream
 */
public static void toXml(Document doc, OutputStream out) throws IOException {
    try {
        DOMSource domSource = new DOMSource(doc);
        StreamResult result = new StreamResult(out);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.VERSION, doc.getXmlVersion());
        transformer.transform(domSource, result);
    } catch (TransformerException e) {
        throw new IOException("unable to transform dom to a stream");
    }
}

From source file:com.milaboratory.util.CompressionType.java

private static InputStream createInputStream(CompressionType ct, InputStream is) throws IOException {
    switch (ct) {
    case None:/*www.j a  va2 s  . c om*/
        return is;
    case GZIP:
        return new GZIPInputStream(is, 2048);
    case BZIP2:
        CompressorStreamFactory factory = new CompressorStreamFactory();
        try {
            return factory.createCompressorInputStream(CompressorStreamFactory.BZIP2,
                    new BufferedInputStream(is));
        } catch (CompressorException e) {
            throw new IOException(e);
        }
    }
    throw new NullPointerException();
}

From source file:Main.java

/**
 * get all the classes name in "classes.dex", "classes2.dex", ....
 *
 * @param context the application context
 * @return all the classes name//  ww  w.  ja  v  a  2s.c o m
 * @throws PackageManager.NameNotFoundException
 * @throws IOException
 */
public static List<String> getAllClasses(Context context)
        throws PackageManager.NameNotFoundException, IOException {
    List<String> classNames = new ArrayList<String>();
    for (String path : getSourcePaths(context)) {
        try {
            DexFile dexfile = null;
            if (path.endsWith(EXTRACTED_SUFFIX)) {
                //NOT use new DexFile(path), because it will throw "permission error in /data/dalvik-cache"
                dexfile = DexFile.loadDex(path, path + ".tmp", 0);
            } else {
                dexfile = new DexFile(path);
            }
            Enumeration<String> dexEntries = dexfile.entries();
            while (dexEntries.hasMoreElements()) {
                classNames.add(dexEntries.nextElement());
            }
        } catch (IOException e) {
            throw new IOException("Error at loading dex file '" + path + "'");
        }
    }
    return classNames;
}

From source file:com.skcraft.launcher.persistence.Persistence.java

/**
 * Save an object to file.//from w  ww  .  j a v a2s  .c  om
 *
 * @param object the object
 * @throws java.io.IOException on save error
 */
public static void commit(@NonNull Object object) throws IOException {
    ByteSink sink;
    synchronized (bound) {
        sink = bound.get(object);
        if (sink == null) {
            throw new IOException("Cannot persist unbound object: " + object);
        }
    }

    Closer closer = Closer.create();
    try {
        OutputStream os = closer.register(sink.openBufferedStream());
        mapper.writeValue(os, object);
    } finally {
        closer.close();
    }
}

From source file:Main.java

public static void deleteChildrenIgnoreFirstLevel(File target, String strIgnore) throws IOException {
    if (!target.exists())
        return;/*from   ww w. j a  va  2  s. com*/

    if (target.isDirectory()) {
        String[] children = target.list();
        for (int i = 0; i != children.length; ++i) {
            File f = new File(target, children[i]);
            if (f.isDirectory())
                deleteRecursively(f);
            else if (!f.getName().startsWith(strIgnore)) {
                if (!f.delete())
                    throw new IOException("Can not delete " + f.getAbsolutePath());
            }
        }
    }
}

From source file:com.atlassian.labs.bamboo.git.edu.nyu.cs.javagit.client.cli.ProcessUtilities.java

/**
 * Start a process.//from   w  w  w.  j  a  v a 2 s  .  c o  m
 *
 * @param pb
 *          The <code>ProcessBuilder</code> to use to start the process.
 * @return The started process.
 * @exception IOException
 *              An <code>IOException</code> is thrown if there is trouble starting the
 *              sub-process.
 */
public static Process startProcess(ProcessBuilder pb) throws IOException {
    try {
        return pb.start();
    } catch (IOException e) {
        IOException toThrow = new IOException(ExceptionMessageMap.getMessage("020100"));
        toThrow.initCause(e);
        throw toThrow;
    }
}

From source file:Main.java

/**
 * Decompresses the given byte[] and returns the Object.
 * //ww  w.ja v a  2s .c  o m
 * @param <T> Type of expected Object
 * @param bytes compressed byte[]
 * @param bufferSize size of buffer to be used (in bytes)
 * 
 * @return decompressed Object
 * 
 * @throws IOException if failed to decompress
 * @throws ClassCastException if cannot cast to specified type
 */
@SuppressWarnings("unchecked")
/* Ignore Unchecked Cast Warning */
public static <T> T decompress(byte[] bytes, int bufferSize) throws IOException, ClassCastException {

    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(bufferSize);
        Inflater inflater = new Inflater();
        inflater.setInput(bytes);

        // Decompress
        byte[] buf = new byte[bufferSize];
        while (!inflater.finished()) {
            int count = inflater.inflate(buf);
            bos.write(buf, 0, count);
        }
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));

        return (T) ois.readObject();
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:gov.nih.nci.cagrid.introduce.servicetools.FilePersistenceHelper.java

public static File getDefaultStorageDirectory(File baseDir, Class beanClass) throws IOException {
    if (beanClass == null) {
        return null;
    }//from  w w  w .ja v a2 s  .  c o m
    String fullClassName = beanClass.getName();
    String className = fullClassName;
    int pos = className.lastIndexOf('.');
    if (pos != -1) {
        className = className.substring(pos + 1);
    }

    String dir = baseDir.getAbsolutePath() + File.separatorChar + className;

    File storageDir = new File(dir);
    if (!storageDir.getCanonicalPath().startsWith(baseDir.getCanonicalPath())) {
        throw new IOException("invalidStorageDir: " + dir);
    }

    return storageDir;
}

From source file:com.ibm.watson.developer_cloud.util.ResponseUtil.java

/**
 * Return a {@link JsonElement} representation of the response.
 * /*from   ww w  .j a v  a2 s  .co m*/
 * @param response
 *            the HttpResponse
 * @return the content body as JSON
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static JsonElement getJsonElement(HttpResponse response) throws IOException {
    final String json = getString(response);
    if (json == null || json.length() == 0)
        throw new IOException("JSON response is empty");

    JsonElement element = new JsonParser().parse(json);
    return element;
}

From source file:de.tudarmstadt.ukp.dkpro.core.mallet.lda.MalletLdaTopicModelUtils.java

/**
 * Retrieve the top n topic words for each topic in the given model.
 * //from   w w  w .java 2s . co  m
 * @param modelFile
 *            the model file
 * @param nWords
 *            the maximum number of words to retrieve
 * @param normalize
 *            normalize the word weights ?
 * 
 * @return a list of maps where each map represents a topic, mapping words to weights
 * @throws IOException
 *             if the model cannot be read
 */
public static List<Map<String, Double>> getTopWords(File modelFile, int nWords, boolean normalize)
        throws IOException {
    LOGGER.info("Reading model file " + modelFile + "...");
    ParallelTopicModel model;
    try {
        model = ParallelTopicModel.read(modelFile);
    } catch (Exception e) {
        throw new IOException(e);
    }
    Alphabet alphabet = model.getAlphabet();

    List<Map<String, Double>> topics = new ArrayList<>(model.getNumTopics());

    /* iterate over topics */
    for (TreeSet<IDSorter> topic : model.getSortedWords()) {
        Map<String, Double> topicWords = new HashMap<>(nWords);

        /* iterate over word IDs in topic (sorted by weight) */
        for (IDSorter id : topic) {
            double weight = normalize ? id.getWeight() / alphabet.size() : id.getWeight(); // normalize
            String word = (String) alphabet.lookupObject(id.getID());

            topicWords.put(word, weight);

            if (topicWords.size() >= nWords) {
                break; // go to next topic
            }
        }
        topics.add(topicWords);
    }
    return topics;
}