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:jetbrains.exodus.util.CompressBackupUtil.java

@NotNull
public static File backup(@NotNull final Backupable target, @NotNull final File backupRoot,
        @Nullable final String backupNamePrefix, final boolean zip) throws Exception {
    if (!backupRoot.exists() && !backupRoot.mkdirs()) {
        throw new IOException("Failed to create " + backupRoot.getAbsolutePath());
    }/*from  w w  w . ja v  a2  s .  co  m*/
    final File backupFile;
    final BackupStrategy strategy = target.getBackupStrategy();
    strategy.beforeBackup();
    try {
        final ArchiveOutputStream archive;
        if (zip) {
            final String fileName = getTimeStampedZipFileName();
            backupFile = new File(backupRoot,
                    backupNamePrefix == null ? fileName : backupNamePrefix + fileName);
            final ZipArchiveOutputStream zipArchive = new ZipArchiveOutputStream(
                    new BufferedOutputStream(new FileOutputStream(backupFile)));
            zipArchive.setLevel(Deflater.BEST_COMPRESSION);
            archive = zipArchive;
        } else {
            final String fileName = getTimeStampedTarGzFileName();
            backupFile = new File(backupRoot,
                    backupNamePrefix == null ? fileName : backupNamePrefix + fileName);
            archive = new TarArchiveOutputStream(
                    new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(backupFile))));
        }
        try (ArchiveOutputStream aos = archive) {
            for (final BackupStrategy.FileDescriptor fd : strategy.listFiles()) {
                if (strategy.isInterrupted()) {
                    break;
                }
                final File file = fd.getFile();
                if (file.isFile()) {
                    final long fileSize = Math.min(fd.getFileSize(), strategy.acceptFile(file));
                    if (fileSize > 0L) {
                        archiveFile(aos, fd.getPath(), file, fileSize);
                    }
                }
            }
        }
        if (strategy.isInterrupted()) {
            logger.info("Backup interrupted, deleting \"" + backupFile.getName() + "\"...");
            IOUtil.deleteFile(backupFile);
        } else {
            logger.info("Backup file \"" + backupFile.getName() + "\" created.");
        }
    } catch (Throwable t) {
        strategy.onError(t);
        throw ExodusException.toExodusException(t, "Backup failed");
    } finally {
        strategy.afterBackup();
    }
    return backupFile;
}

From source file:com.cloudera.knittingboar.utils.DataUtils.java

public static synchronized File getTwentyNewsGroupDir() throws IOException {
    if (twentyNewsGroups != null) {
        return twentyNewsGroups;
    }/*w ww  .j  a v a  2s . c  om*/
    // mac gives unique tmp each run and we want to store this persist
    // this data across restarts
    File tmpDir = new File("/tmp");
    if (!tmpDir.isDirectory()) {
        tmpDir = new File(System.getProperty("java.io.tmpdir"));
    }
    File baseDir = new File(tmpDir, TWENTY_NEWS_GROUP_LOCAL_DIR);
    if (!(baseDir.isDirectory() || baseDir.mkdir())) {
        throw new IOException("Could not mkdir " + baseDir);
    }
    File tarFile = new File(baseDir, TWENTY_NEWS_GROUP_TAR_FILE_NAME);

    if (!tarFile.isFile()) {
        FileUtils.copyURLToFile(new URL(TWENTY_NEWS_GROUP_TAR_URL), tarFile);
    }

    Process p = Runtime.getRuntime()
            .exec(String.format("tar -C %s -xvf %s", baseDir.getAbsolutePath(), tarFile.getAbsolutePath()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    System.out.println("Here is the standard error of the command (if any):\n");
    String s;
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
    }
    stdError.close();
    twentyNewsGroups = baseDir;
    return twentyNewsGroups;
}

From source file:Main.java

/**
 * Makes a directory, including any necessary but nonexistent parent
 * directories. If a file already exists with specified name but it is
 * not a directory then an IOException is thrown.
 * If the directory cannot be created (or does not already exist)
 * then an IOException is thrown.//from ww w. j  a  va  2s  . c o  m
 *
 * @param directory directory to create, must not be {@code null}
 * @throws NullPointerException if the directory is {@code null}
 * @throws IOException  if the directory cannot be created or the file already exists but is not a directory
 */
public static void forceMkdir(File directory) throws IOException {
    if (directory.exists()) {
        if (!directory.isDirectory()) {
            String message = "File " + directory + " exists and is "
                    + "not a directory. Unable to create directory.";
            throw new IOException(message);
        }
    } else {
        if (!directory.mkdirs()) {
            // Double-check that some other thread or process hasn't made
            // the directory in the background
            if (!directory.isDirectory()) {
                String message = "Unable to create directory " + directory;
                throw new IOException(message);
            }
        }
    }
}

From source file:com.buaa.cfs.nfs3.request.CREATE3Request.java

public static CREATE3Request deserialize(XDR xdr) throws IOException {
    FileHandle handle = readHandle(xdr);
    String name = xdr.readString();
    int mode = xdr.readInt();
    SetAttr3 objAttr = new SetAttr3();
    long verf = 0;
    if ((mode == Nfs3Constant.CREATE_UNCHECKED) || (mode == Nfs3Constant.CREATE_GUARDED)) {
        objAttr.deserialize(xdr);//from   w  w w. j  a  v  a2 s .c o m
    } else if (mode == Nfs3Constant.CREATE_EXCLUSIVE) {
        verf = xdr.readHyper();
    } else {
        throw new IOException("Wrong create mode:" + mode);
    }
    return new CREATE3Request(handle, name, mode, objAttr, verf);
}

From source file:mesclasses.util.EleveFileUtil.java

public static String copyFileForEleve(Eleve eleve, File file, String type) throws IOException {
    File eleveDir = getEleveDirWithType(eleve, type);
    eleveDir.mkdirs();/*from www . j  a v  a 2  s. c om*/
    String fileName = FilenameUtils.getName(file.getPath());
    File newFile = new File(eleveDir.getPath() + File.separator + fileName);
    if (newFile.exists()) {
        throw new IOException(
                "Le fichier " + fileName + " de type " + type + " existe dj pour " + eleve.getFirstName());
    }
    FileUtils.copyFile(file, newFile);
    return newFile.getPath();
}

From source file:com.yahoo.rdl.maven.ProcessRunner.java

public String run(List<String> command, ProcessBuilder processBuilder) throws IOException {
    Process process = processBuilder.start();
    try (StreamConsumer stdout = new StreamConsumer(process.getInputStream()).start()) {
        try (StreamConsumer stderr = new StreamConsumer(process.getErrorStream()).start()) {
            if (!process.waitFor(10, TimeUnit.SECONDS)) {
                throw new IOException("Process took longer than 10 seconds to execute: " + command);
            }/*  w w w.  j  a v a2  s.  com*/
            if (process.exitValue() != 0) {
                String s = stderr.getContents();
                throw new IOException("command '" + StringUtils.join(command, " ") + "' produced error: " + s);
            }
        }
        return stdout.getContents();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.qwazr.graph.GraphManager.java

public synchronized static Class<? extends GraphServiceInterface> load(ExecutorService executorService,
        File dataDirectory) throws IOException {
    if (INSTANCE != null)
        throw new IOException("Already loaded");
    File graphDirectory = new File(dataDirectory, SERVICE_NAME_GRAPH);
    if (!graphDirectory.exists())
        graphDirectory.mkdir();/*from  w  w  w  . jav  a  2 s.  co m*/
    try {
        INSTANCE = new GraphManager(executorService, graphDirectory);
        for (String name : INSTANCE.nameSet())
            INSTANCE.addNewInstance(name, INSTANCE.get(name));
        return GraphServiceImpl.class;
    } catch (ServerException | DatabaseException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/** Write a DOM to a file. */
public static void writeXML(Document document, File file) throws IOException {
    // save the DOM to file
    StreamResult result = new StreamResult(new BufferedOutputStream(new FileOutputStream(file)));
    TransformerFactory transFactory = TransformerFactory.newInstance();
    try {//from   w w  w.java  2 s .  c  o  m
        Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty("indent", "yes");
        transformer.transform(new DOMSource(document), result);
    } catch (TransformerConfigurationException ex) {
        throw new IOException(ex.getMessage());
    } catch (TransformerException ex) {
        throw new IOException(ex.getMessage());
    }
    result.getOutputStream().close();
}

From source file:Main.java

/**
 * Opens a {@link FileInputStream} for the specified file, providing better
 * error messages than simply calling <code>new FileInputStream(file)</code>.
 * <p/>//from  ww w.  j ava 2 s.c o  m
 * At the end of the method either the stream will be successfully opened,
 * or an exception will have been thrown.
 * <p/>
 * An exception is thrown if the file does not exist.
 * An exception is thrown if the file object exists but is a directory.
 * An exception is thrown if the file exists but cannot be read.
 *
 * @param file the file to open for input, must not be {@code null}
 * @return a new {@link FileInputStream} for the specified file
 * @throws FileNotFoundException if the file does not exist
 * @throws IOException           if the file object is a directory
 * @throws IOException           if the file cannot be read
 * @since 1.3
 */
public static FileInputStream openInputStream(File file) throws IOException {
    if (file.exists()) {
        if (file.isDirectory()) {
            throw new IOException("File '" + file + "' exists but is a directory");
        }
        if (file.canRead() == false) {
            throw new IOException("File '" + file + "' cannot be read");
        }
    } else {
        throw new FileNotFoundException("File '" + file + "' does not exist");
    }
    return new FileInputStream(file);
}

From source file:be.emich.labs.villohelper.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {/* www  .  java2 s  . c om*/
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[] { new EasyX509TrustManager(null) }, null);
        return context;
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}