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

public static long getCommentLength(final FileChannel fileChannel) throws IOException {
    // End of central directory record (EOCD)
    // Offset    Bytes     Description[23]
    // 0           4       End of central directory signature = 0x06054b50
    // 4           2       Number of this disk
    // 6           2       Disk where central directory starts
    // 8           2       Number of central directory records on this disk
    // 10          2       Total number of central directory records
    // 12          4       Size of central directory (bytes)
    // 16          4       Offset of start of central directory, relative to start of archive
    // 20          2       Comment length (n)
    // 22          n       Comment
    // For a zip with no archive comment, the
    // end-of-central-directory record will be 22 bytes long, so
    // we expect to find the EOCD marker 22 bytes from the end.

    final long archiveSize = fileChannel.size();
    if (archiveSize < ZIP_EOCD_REC_MIN_SIZE) {
        throw new IOException("APK too small for ZIP End of Central Directory (EOCD) record");
    }/*from  ww  w  .j  a  va 2 s  .  com*/
    // ZIP End of Central Directory (EOCD) record is located at the very end of the ZIP archive.
    // The record can be identified by its 4-byte signature/magic which is located at the very
    // beginning of the record. A complication is that the record is variable-length because of
    // the comment field.
    // The algorithm for locating the ZIP EOCD record is as follows. We search backwards from
    // end of the buffer for the EOCD record signature. Whenever we find a signature, we check
    // the candidate record's comment length is such that the remainder of the record takes up
    // exactly the remaining bytes in the buffer. The search is bounded because the maximum
    // size of the comment field is 65535 bytes because the field is an unsigned 16-bit number.
    final long maxCommentLength = Math.min(archiveSize - ZIP_EOCD_REC_MIN_SIZE, UINT16_MAX_VALUE);
    final long eocdWithEmptyCommentStartPosition = archiveSize - ZIP_EOCD_REC_MIN_SIZE;
    for (int expectedCommentLength = 0; expectedCommentLength <= maxCommentLength; expectedCommentLength++) {
        final long eocdStartPos = eocdWithEmptyCommentStartPosition - expectedCommentLength;

        final ByteBuffer byteBuffer = ByteBuffer.allocate(4);
        fileChannel.position(eocdStartPos);
        fileChannel.read(byteBuffer);
        byteBuffer.order(ByteOrder.LITTLE_ENDIAN);

        if (byteBuffer.getInt(0) == ZIP_EOCD_REC_SIG) {
            final ByteBuffer commentLengthByteBuffer = ByteBuffer.allocate(2);
            fileChannel.position(eocdStartPos + ZIP_EOCD_COMMENT_LENGTH_FIELD_OFFSET);
            fileChannel.read(commentLengthByteBuffer);
            commentLengthByteBuffer.order(ByteOrder.LITTLE_ENDIAN);

            final int actualCommentLength = commentLengthByteBuffer.getShort(0);
            if (actualCommentLength == expectedCommentLength) {
                return actualCommentLength;
            }
        }
    }
    throw new IOException("ZIP End of Central Directory (EOCD) record not found");
}

From source file:com.cloudera.training.metrics.JobHistoryHelper.java

public static JobHistory.JobInfo getJobInfoFromCliArgs(Configuration conf, String... args) throws IOException {

    for (String s : args) {
        System.out.println(s);//from w w  w.  j  a  v a2  s.c o m
    }
    String usage = "Expected 2 arguments, either --hdfsdir <dir> or --localfile <path>";
    if (args.length != 2) {
        throw new IOException(usage);
    }
    if ("--hdfsdir".equals(args[0])) {
        return getJobInfoFromHdfsOutputDir(args[1], conf);
    } else if ("--localfile".equals(args[0])) {
        return getJobInfoFromLocalFile(args[1], conf);
    }
    throw new IOException("Unexpected option '" + args[0] + "' \n" + usage);
}

From source file:edu.msu.cme.rdp.rarefaction.RarefactionPlotter.java

public static void plotRarefaction(Map<ClusterSample, List<RarefactionResult>> rarefactionResults,
        File outputDirectory) throws IOException {
    if (!outputDirectory.isDirectory()) {
        throw new IOException(outputDirectory + " isn't a directory!");
    }//from  www .  j  ava 2  s .co m

    for (ClusterSample sample : rarefactionResults.keySet()) {
        List<RarefactionResult> resultsToPlot = new ArrayList();

        int currCutoff = 0;
        RarefactionResult lastResult = null;
        for (RarefactionResult result : rarefactionResults.get(sample)) {
            if (result.getDistance() <= interestedPoints[currCutoff]) {
                lastResult = result;
            } else {
                if (lastResult != null) {
                    resultsToPlot.add(lastResult);

                    if (++currCutoff >= interestedPoints.length) {
                        break;
                    }
                }
            }
        }

        plotToFile(resultsToPlot, sample.getSeqs(), sample.getName() + " Rarefaction",
                new File(outputDirectory, sample.getName() + "_rarefaction.png"));
    }

}

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();/*from w w  w .  jav 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.qwazr.library.LibraryManagerImpl.java

static synchronized void load(File dataDirectory, TrackedDirectory etcTracker) throws IOException {
    if (INSTANCE != null)
        throw new IOException("Already loaded");
    INSTANCE = new LibraryManagerImpl(dataDirectory, etcTracker);
    etcTracker.register(INSTANCE);/*from   w w  w .  j a  va2  s  .  co m*/
}

From source file:com.likethecolor.alchemy.api.validator.OutputStatusValidator.java

private static void validate(final Response.STATUS status, final String statusInfo,
        final String originalJsonString) throws IOException {
    if (null == status || status != Response.STATUS.OK) {
        if (!StringUtils.isBlank(statusInfo)) {
            throw new IOException(
                    "Error making API call: " + statusInfo + " - original json string: " + originalJsonString);
        }// w  ww  . j a  v a 2 s  .  c om
        throw new IOException(
                "Error making API call: " + status + " - original json string: " + originalJsonString);
    }
}

From source file:Main.java

public static void pushFileFromRAW(Context mContext, File outputFile, int RAW, boolean Override)
        throws IOException {
    if (!outputFile.exists() || Override) {
        if (Override && outputFile.exists())
            if (!outputFile.delete()) {
                throw new IOException(outputFile.getName() + " can't be deleted!");
            }// w  ww  .j ava2s.  c o  m
        InputStream is = mContext.getResources().openRawResource(RAW);
        OutputStream os = new FileOutputStream(outputFile);
        byte[] data = new byte[is.available()];
        is.read(data);
        os.write(data);
        is.close();
        os.close();
    }
}

From source file:io.proscript.jlight.Runtime.java

public static void run(CommandLine line) throws IOException {

    Environment environment = new Environment();

    if (1 == line.getArgList().size()) {
        File cwdCandidate = new File(line.getArgList().get(0));
        if (cwdCandidate.isDirectory()) {
            environment.setCwd(cwdCandidate);
        } else {//from  www. j  av  a2s.  c om
            throw new IOException("Last argument must be valid source root directory");
        }
    } else {
        environment.setCwd(new File(System.getProperty("user.dir")));
    }

    if (line.hasOption("port")) {
        environment.setPort(Integer.valueOf(line.getOptionValue("port")));
    }

    if (line.hasOption("host")) {
        environment.setHost(line.getOptionValue("host"));
    }

    environment.setCacheDirectory(new File(environment.getCwd().toString() + "/.jlcache"));
    environment.setMainClassName(line.getOptionValue("class"));

    CacheManager cacheManager = new CacheManager(environment);

    try {
        cacheManager.initialize();
    } catch (IOException e) {
        log.log(Level.SEVERE, "Failed to initialize class file cache: %s", e.getMessage());
        return;
    }

    Collection<File> javaFiles = SourcesLocator.locateRecursive(environment.getCwd());

    ApplicationCompiler compiler = new ApplicationCompiler(environment.getCacheDirectory());

    boolean result = false;

    try {
        result = compiler.compile(javaFiles);
    } catch (IOException e) {
        log.log(Level.SEVERE, "Compilation failed: %s", e.getMessage());
        return;
    }

    if (!result) {
        for (Diagnostic diagnostic : compiler.getLastDiagnosticCollector().getDiagnostics()) {
            System.out.println(diagnostic.getMessage(Locale.getDefault()));
            LogRecord record = new LogRecord(Level.SEVERE, diagnostic.getMessage(Locale.getDefault()));
            log.log(record);
        }
    } else {

        Application application = buildApplication(environment);
        ThreadedHTTPServer server = new ThreadedHTTPServer(environment);
        server.run(application);
    }

    try {
        cacheManager.destroy();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/**
 * recursively delete//ww  w  .  j a  v a2  s  . c  o m
 *
 * @param dir
 * @throws java.io.IOException
 */
public static void deleteDirectoryRecursively(File dir) throws IOException {
    File[] files = dir.listFiles();
    if (files == null) {
        throw new IllegalArgumentException("not a directory: " + dir);
    }
    for (File file : files) {
        if (file.isDirectory()) {
            deleteDirectoryRecursively(file);
        }
        if (!file.delete()) {
            throw new IOException("failed to delete file: " + file);
        }
    }
}

From source file:Main.java

public static byte[] stream2Bytes(InputStream in, int length) throws IOException {
    byte[] bytes = new byte[length];
    int count;/*from  w  w w  .  j  a  va2  s.  com*/
    int pos = 0;
    while (pos < length && ((count = in.read(bytes, pos, length - pos)) != -1)) {
        pos += count;
    }
    if (pos != length) {
        throw new IOException("Expected " + length + " bytes, read " + pos + " bytes");
    }
    return bytes;
}