Example usage for java.io FileNotFoundException FileNotFoundException

List of usage examples for java.io FileNotFoundException FileNotFoundException

Introduction

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

Prototype

public FileNotFoundException(String s) 

Source Link

Document

Constructs a FileNotFoundException with the specified detail message.

Usage

From source file:com.yifanlu.PSXperiaTool.Extractor.CrashBandicootExtractor.java

private void processConfig() throws IOException, UnsupportedOperationException {
    long crc32 = ZpakCreate.getCRC32(mApkFile);
    String crcString = Long.toHexString(crc32).toUpperCase();
    InputStream inConfig = null;//from   w w  w.  j  a v a2 s . co m
    if ((inConfig = PSXperiaTool.class
            .getResourceAsStream("/resources/patches/" + crcString + "/config.xml")) == null) {
        throw new FileNotFoundException("Cannot find config for this APK (CRC32: " + crcString + ")");
    }
    Properties config = new Properties();
    config.loadFromXML(inConfig);
    inConfig.close();
    Logger.info("Identified " + config.getProperty("game_name", "Unknown Game") + " "
            + config.getProperty("game_region") + " Version " + config.getProperty("game_version", "Unknown")
            + ", CRC32: " + config.getProperty("game_crc32", "Unknown"));
    if (config.getProperty("valid", "yes").equals("no"))
        throw new UnsupportedOperationException("This APK is not supported.");
    Logger.verbose("Copying config files.");
    FileUtils.copyInputStreamToFile(
            PSXperiaTool.class.getResourceAsStream("/resources/patches/" + crcString + "/config.xml"),
            new File(mOutputDir, "/config/config.xml"));
    FileUtils.copyInputStreamToFile(
            PSXperiaTool.class.getResourceAsStream("/resources/patches/" + crcString + "/filelist.txt"),
            new File(mOutputDir, "/config/filelist.txt"));
    FileUtils.copyInputStreamToFile(
            PSXperiaTool.class
                    .getResourceAsStream("/resources/patches/" + crcString + "/stringReplacements.txt"),
            new File(mOutputDir, "/config/stringReplacements.txt"));
    String emulatorPatch = config.getProperty("emulator_patch", "");
    String gamePatch = config.getProperty("iso_patch", "");
    if (!gamePatch.equals("")) {
        FileUtils.copyInputStreamToFile(
                PSXperiaTool.class.getResourceAsStream("/resources/patches/" + crcString + "/" + gamePatch),
                new File(mOutputDir, "/config/game-patch.bin"));
    }
    if (!emulatorPatch.equals("")) {
        FileUtils.copyInputStreamToFile(
                PSXperiaTool.class.getResourceAsStream("/resources/patches/" + crcString + "/" + emulatorPatch),
                new File(mOutputDir, "/config/" + emulatorPatch));
    }
}

From source file:ml.dmlc.xgboost4j.java.NativeLibrary.java

private static File extract(String libPath, ClassLoader classLoader)
        throws IOException, IllegalArgumentException {

    // Split filename to prefix and suffix (extension)
    String filename = libPath.substring(libPath.lastIndexOf('/') + 1);
    int lastDotIdx = filename.lastIndexOf('.');
    String prefix = "";
    String suffix = null;/*  w  w w .  j  a  v a  2 s .c  om*/
    if (lastDotIdx >= 0 && lastDotIdx < filename.length() - 1) {
        prefix = filename.substring(0, lastDotIdx);
        suffix = filename.substring(lastDotIdx);
    }

    // Prepare temporary file
    File temp = File.createTempFile(prefix, suffix);
    temp.deleteOnExit();

    // Open and check input stream
    InputStream is = classLoader.getResourceAsStream(libPath);
    if (is == null) {
        throw new FileNotFoundException("File " + libPath + " was not found inside JAR.");
    }

    // Open output stream and copy data between source file in JAR and the temporary file
    try {
        Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } finally {
        is.close();
    }

    return temp;
}

From source file:org.taverna.server.master.admin.AdminBean.java

protected byte[] getResource(String name) throws IOException {
    if (AdminBean.class.getResource(name) == null)
        throw new FileNotFoundException(name);
    return IOUtils.toByteArray(AdminBean.class.getResourceAsStream(name));
}

From source file:ffx.potential.utils.PotentialsDataConverter.java

/**
 * Switches between various default get-file methods for different data
 * structure types.//  ww  w . java  2s . c  o  m
 *
 * @param data Data structure to find file file
 * @return Source file
 * @throws FileNotFoundException If no file could be found
 */
public static File getDefaultFile(Object data) throws FileNotFoundException {
    if (data instanceof Structure) {
        return getBiojavaFile((Structure) data);
    } // Insert else-ifs for other data structures here.
    throw new FileNotFoundException("Could not find a file for data structure.");
}

From source file:cn.com.iscs.base.util.XMLProperties.java

/**
 * Creates a new XMLPropertiesTest object.
 * /* w  w w. j a v a 2  s  . c  o m*/
 * @param file
 *          the file that properties should be read from and written to.
 * @throws java.io.IOException
 *           if an error occurs loading the properties.
 */
public XMLProperties(File file) throws IOException {
    this.file = file;
    if (!file.exists()) {
        // Attempt to recover from this error case by seeing if the
        // tmp file exists. It's possible that the rename of the
        // tmp file failed the last time Jive was running,
        // but that it exists now.
        File tempFile;
        tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
        if (tempFile.exists()) {
            System.err.print("WARNING: " + file.getName() + " was not found, but temp file from "
                    + "previous write operation was. Attempting automatic recovery."
                    + " Please check file for data consistency.");
            tempFile.renameTo(file);
        }
        // There isn't a possible way to recover from the file not
        // being there, so throw an error.
        else {
            throw new FileNotFoundException("XML properties file does not exist: " + file.getName());
        }
    }
    // Check read and write privs.
    if (!file.canRead()) {
        throw new IOException("XML properties file must be readable: " + file.getName());
    }
    if (!file.canWrite()) {
        throw new IOException("XML properties file must be writable: " + file.getName());
    }

    FileReader reader = new FileReader(file);
    buildDoc(reader);
}

From source file:com.frederikam.gensokyobot.Config.java

/**
 * Makes sure the requested config file exists in the current format. Will attempt to migrate old formats to new ones
 * old files will be renamed to filename.ext.old to preserve any data
 *
 * @param name relative name of a config file, without the file extension
 * @return a handle on the requested file
 *//*from www . ja  v a2s  .com*/
private static File loadConfigFile(String name) throws IOException {
    String yamlPath = "./" + name + ".yaml";
    String jsonPath = "./" + name + ".json";
    File yamlFile = new File(yamlPath);
    if (!yamlFile.exists() || yamlFile.isDirectory()) {
        log.warn("Could not find file '" + yamlPath + "', looking for legacy '" + jsonPath + "' to rewrite");
        File json = new File(jsonPath);
        if (!json.exists() || json.isDirectory()) {
            //file is missing
            log.error("No " + name + " file is present. Bot cannot run without it. Check the documentation.");
            throw new FileNotFoundException("Neither '" + yamlPath + "' nor '" + jsonPath + "' present");
        } else {
            //rewrite the json to yaml
            Yaml yaml = new Yaml();
            String fileStr = FileUtils.readFileToString(json, "UTF-8");
            //remove tab character from json file to make it a valid YAML file
            fileStr = fileStr.replaceAll("\t", "");
            @SuppressWarnings("unchecked")
            Map<String, Object> configFile = (Map) yaml.load(fileStr);
            yaml.dump(configFile, new FileWriter(yamlFile));
            Files.move(Paths.get(jsonPath), Paths.get(jsonPath + ".old"), REPLACE_EXISTING);
            log.info("Migrated file '" + jsonPath + "' to '" + yamlPath + "'");
        }
    }

    return yamlFile;
}

From source file:cz.muni.fi.mir.services.FileDirectoryService.java

/**
 * Method used for obtaining SourceDocuments out of given path including
 * subdirectories matching fileName. Check out {@link MathFileVisitor} class
 * which is used for walking, to see the structure of fileName. Method
 * ensures following out of path that has been matched:
 * <ul>//from w  w  w . j  a  v a  2 s  .c  o  m
 * <li>creates formula object</li>
 * <li>as output is set empty ArrayList</li>
 * <li>as content content of given file is set</li>
 * <li>current time is set as insert time</li>
 * <li>result is added into resultList</li>
 * <li>sets logged user as creator</li>
 * </ul>
 * If any error occurs during the reading of file exception is
 * <b>suppressed</b> and logged with error level.
 *
 * @param path root path in which are desired files
 * @param filter regex value used for file matching. If empty default based
 * on {@link #MATCH_PATTERN} is set.
 * @return Formulas found in given folder matched against filter.
 * @throws FileNotFoundException if root path does not exist
 */
public List<Formula> exploreDirectory(Path path, String filter) throws FileNotFoundException {
    if (!Files.exists(path)) {
        throw new FileNotFoundException("Root directory " + path + " not found.");
    }
    if (Tools.getInstance().stringIsEmpty(filter)) {
        filter = MATCH_PATTERN;
    }

    MathFileVisitor mfv = new MathFileVisitor(filter, MathFileVisitor.MathFileVisitorType.GLOB);

    try {
        Files.walkFileTree(path, mfv);
    } catch (IOException ex) {
        logger.error(ex);
    }

    List<Formula> result = new ArrayList<>(mfv.done().size());
    User u = securityContext.getLoggedEntityUser();
    for (Path p : mfv.done()) {
        Formula f = EntityFactory.createFormula();
        f.setOutputs(new ArrayList<CanonicOutput>());
        InputStream is = null;
        try {
            is = Files.newInputStream(p);
            f.setXml(IOUtils.toString(is));
            f.setInsertTime(DateTime.now());
            f.setUser(u);
            result.add(f);
        } catch (IOException ex) {
            logger.error(ex);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ex) {
                    logger.fatal(ex);
                }
            }
        }
    }

    return result;
}

From source file:eu.esdihumboldt.hale.common.headless.impl.WorkspaceServiceImpl.java

/**
 * @see WorkspaceService#getWorkspaceFolder(String)
 *///from   w w  w  .j  ava2s.  c  o m
@Override
public File getWorkspaceFolder(String id) throws FileNotFoundException {
    if (id == null || id.isEmpty()) {
        throw new FileNotFoundException("Invalid workspace ID");
    }

    File workspace = new File(parentDir, id);
    if (!workspace.exists() || !configFile(workspace).exists()) {
        throw new FileNotFoundException("Workspace does not exist");
    }
    return workspace;
}

From source file:de.sub.goobi.helper.FilesystemHelper.java

/**
 * This function implements file renaming. Renaming of files is full of
 * mischief under Windows which unaccountably holds locks on files.
 * Sometimes running the JVMs garbage collector puts things right.
 *
 * @param oldFileName/*  w w w  .  j  a  va 2  s .c  o m*/
 *            File to move or rename
 * @param newFileName
 *            New file name / destination
 * @throws IOException
 *             is thrown if the rename fails permanently
 * @throws FileNotFoundException
 *             is thrown if old file (source file of renaming) does not
 *             exists
 */
public static void renameFile(String oldFileName, String newFileName) throws IOException {
    final int SLEEP_INTERVAL_MILLIS = 20;
    final int MAX_WAIT_MILLIS = 150000; // 2 minutes
    File oldFile;
    File newFile;
    boolean success;
    int millisWaited = 0;

    if ((oldFileName == null) || (newFileName == null)) {
        return;
    }

    oldFile = new File(oldFileName);
    newFile = new File(newFileName);

    if (!oldFile.exists()) {
        if (logger.isDebugEnabled()) {
            logger.debug("File " + oldFileName + " does not exist for renaming.");
        }
        throw new FileNotFoundException(oldFileName + " does not exist for renaming.");
    }

    if (newFile.exists()) {
        String message = "Renaming of " + oldFileName + " into " + newFileName + " failed: Destination exists.";
        logger.error(message);
        throw new IOException(message);
    }

    do {
        if (SystemUtils.IS_OS_WINDOWS && millisWaited == SLEEP_INTERVAL_MILLIS) {
            if (logger.isEnabledFor(Level.WARN)) {
                logger.warn("Renaming " + oldFileName
                        + " failed. This is Windows. Running the garbage collector may yield good results. Forcing immediate garbage collection now!");
            }
            System.gc();
        }
        success = oldFile.renameTo(newFile);
        if (!success) {
            if (millisWaited == 0 && logger.isInfoEnabled()) {
                logger.info("Renaming " + oldFileName + " failed. File may be locked. Retrying...");
            }
            try {
                Thread.sleep(SLEEP_INTERVAL_MILLIS);
            } catch (InterruptedException e) {
            }
            millisWaited += SLEEP_INTERVAL_MILLIS;
        }
    } while (!success && millisWaited < MAX_WAIT_MILLIS);

    if (!success) {
        logger.error("Rename " + oldFileName + " failed. This is a permanent error. Giving up.");
        throw new IOException("Renaming of " + oldFileName + " into " + newFileName + " failed.");
    }

    if (millisWaited > 0 && logger.isInfoEnabled()) {
        logger.info("Rename finally succeeded after" + Integer.toString(millisWaited) + " milliseconds.");
    }
}

From source file:dk.statsbiblioteket.util.qa.PackageScanner.java

/**
 * Scan QA annotations for a file or recursively through a directory.
 *
 * @param source The source./*from  w ww  .java  2 s  .co m*/
 * @throws IOException If there is an error reading a class file.
 */
protected final void scan(String source) throws IOException {
    if (source == null) {
        throw new NullPointerException("Source argument is null");
    }
    File sourceFile = new File(baseSource, source);

    if (!sourceFile.exists()) {
        throw new FileNotFoundException(sourceFile.toString());
    }

    if (sourceFile.isFile()) {
        scanFile(source);
    } else {
        scanDirectory(source);
    }
}