Java 类java.io.FileNotFoundException 实例源码

项目:monarch    文件:HydraLineMapper.java   
private String getDiskStoreIdFromInitFile(File dir, String fileName)
    throws FileNotFoundException, IOException {
  FileInputStream fis = new FileInputStream(new File(dir, fileName));
  try {
    byte[] bytes = new byte[1 + 8 + 8];
    fis.read(bytes);
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    // Skip the record type.
    buffer.get();
    long least = buffer.getLong();
    long most = buffer.getLong();
    UUID id = new UUID(most, least);
    return id.toString();
  } finally {
    fis.close();
  }
}
项目:FireFiles    文件:RootedStorageProvider.java   
@Override
public String renameDocument(String documentId, String displayName) throws FileNotFoundException {
    // Since this provider treats renames as generating a completely new
    // docId, we're okay with letting the MIME type change.
    displayName = FileUtils.buildValidFatFilename(displayName);

    final RootFile before = getRootFileForDocId(documentId);
    final RootFile after = new RootFile(before.getParent(), displayName);

    if(!RootCommands.renameRootTarget(before, after)){
        throw new IllegalStateException("Failed to rename " + before);
    }
    final String afterDocId = getDocIdForRootFile(new RootFile(after.getParent(), displayName));
    if (!TextUtils.equals(documentId, afterDocId)) {
        notifyDocumentsChanged(documentId);
        return afterDocId;
    } else {
        return null;
    }
}
项目:jaer    文件:MotionFlowStatistics.java   
void openLog(final String loggingFolder) {
    try {
        filename = loggingFolder + "/ProcessingTime_" + filterClassName
                + DATE_FORMAT.format(new Date()) + ".txt";
        logStream = new PrintStream(new BufferedOutputStream(
                new FileOutputStream(new File(filename))));
        log.log(Level.INFO, "Created motion flow logging file with "
                + "processing time statistics at {0}", filename);
        logStream.println("Processing time statistics of motion flow "
                + "calculation, averaged over event packets.");
        logStream.println("Date: " + new Date());
        logStream.println("Filter used: " + filterClassName);
        logStream.println();
        logStream.println("timestamp [us] | processing time [us]");
    } catch (FileNotFoundException ex) {
        log.log(Level.SEVERE, null, ex);
    }
}
项目:hadoop    文件:S3AFileSystem.java   
private void deleteUnnecessaryFakeDirectories(Path f) throws IOException {
  while (true) {
    try {
      String key = pathToKey(f);
      if (key.isEmpty()) {
        break;
      }

      S3AFileStatus status = getFileStatus(f);

      if (status.isDirectory() && status.isEmptyDirectory()) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("Deleting fake directory " + key + "/");
        }
        s3.deleteObject(bucket, key + "/");
        statistics.incrementWriteOps(1);
      }
    } catch (FileNotFoundException | AmazonServiceException e) {
    }

    if (f.isRoot()) {
      break;
    }

    f = f.getParent();
  }
}
项目:butterfly    文件:AddLine.java   
@Override
protected TOExecutionResult execution(File transformedAppFolder, TransformationContext transformationContext) {
    File fileToBeModified = getAbsoluteFile(transformedAppFolder, transformationContext);

    if (!fileToBeModified.exists()) {
        // TODO Should this be done as pre-validation?
        FileNotFoundException ex = new FileNotFoundException("File to be modified has not been found");
        return TOExecutionResult.error(this, ex);
    }

    TOExecutionResult result = null;

    try {
        FileUtils.fileAppend(fileToBeModified.getAbsolutePath(), EolHelper.findEolDefaultToOs(fileToBeModified));
        FileUtils.fileAppend(fileToBeModified.getAbsolutePath(), newLine);
        String details =  "A new line has been added to file " + getRelativePath(transformedAppFolder, fileToBeModified);
        result = TOExecutionResult.success(this, details);
    } catch (IOException e) {
        result = TOExecutionResult.error(this, e);
    }

    return result;
}
项目:DWSurvey    文件:DocExportUtil.java   
public void createDoc() throws FileNotFoundException{
     /** 创建Document对象(word文档)  */
       Rectangle rectPageSize = new Rectangle(PageSize.A4);
       rectPageSize = rectPageSize.rotate();
       // 创建word文档,并设置纸张的大小
       doc = new Document(PageSize.A4);
       file=new File(path+docFileName);
       fileOutputStream=new FileOutputStream(file);
       /** 建立一个书写器与document对象关联,通过书写器可以将文档写入到输出流中 */
       RtfWriter2.getInstance(doc, fileOutputStream );
       doc.open();
       //设置页边距,上、下25.4毫米,即为72f,左、右31.8毫米,即为90f  
       doc.setMargins(90f, 90f, 72f, 72f);
       //设置标题字体样式,粗体、二号、华文中宋  
       tfont  = DocStyleUtils.setFontStyle("华文中宋", 22f, Font.BOLD);  
       //设置正文内容的字体样式,常规、三号、仿宋_GB2312  
       bfont = DocStyleUtils.setFontStyle("仿宋_GB2312", 16f, Font.NORMAL);
}
项目:hotelApp    文件:DatabaseConnector.java   
/**
 * Attempts to load properties file with database configuration. Must
 * include username, password, database, and hostname.
 *
 * @param configPath path to database properties file
 * @return database properties
 * @throws IOException if unable to properly parse properties file
 * @throws FileNotFoundException if properties file not found
 */
private Properties loadConfig(String configPath) throws FileNotFoundException, IOException {

    // Specify which keys must be in properties file
    Set<String> required = new HashSet<>();
    required.add("username");
    required.add("password");
    required.add("database");
    required.add("hostname");

    // Load properties file
    Properties config = new Properties();
    config.load(new FileReader(configPath));

    // Check that required keys are present
    if (!config.keySet().containsAll(required)) {
        String error = "Must provide the following in properties file: ";
        throw new InvalidPropertiesFormatException(error + required);
    }

    return config;
}
项目:javaide    文件:URLClassPath.java   
private JarFile getJarFile(URL url) throws IOException {
    // Optimize case where url refers to a local jar file
    if (isOptimizable(url)) {
        //HACK
        //FileURLMapper p = new FileURLMapper (url);
        File p = new File(url.getPath());

        if (!p.exists()) {
            throw new FileNotFoundException(p.getPath());
        }
        return new JarFile (p.getPath());
    }
    URLConnection uc = getBaseURL().openConnection();
    uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION);
    return ((JarURLConnection)uc).getJarFile();
}
项目:DecompiledMinecraft    文件:PlayerProfileCache.java   
/**
 * Save the cached profiles to disk
 */
public void save()
{
    String s = this.gson.toJson((Object)this.getEntriesWithLimit(1000));
    BufferedWriter bufferedwriter = null;

    try
    {
        bufferedwriter = Files.newWriter(this.usercacheFile, Charsets.UTF_8);
        bufferedwriter.write(s);
        return;
    }
    catch (FileNotFoundException var8)
    {
        ;
    }
    catch (IOException var9)
    {
        return;
    }
    finally
    {
        IOUtils.closeQuietly((Writer)bufferedwriter);
    }
}
项目:synthea_java    文件:ConceptsTest.java   
@Test
public void testInventoryModule() throws FileNotFoundException {
  Path modulesFolder = Paths.get("src/test/resources/generic");
  Path modulePath = modulesFolder.resolve("example_module.json");

  JsonReader reader = new JsonReader(new FileReader(modulePath.toString()));
  JsonObject module = new JsonParser().parse(reader).getAsJsonObject();

  // example_module has 4 codes:
  // Examplitis condition
  // Examplitol medication
  // Examplotomy_Encounter
  // Examplotomy procedure


  Concepts.inventoryModule(concepts, module);

  assertEquals(4, concepts.cellSet().size());
  assertEquals("Examplitis", concepts.get("SNOMED-CT", "123"));
  assertEquals("Examplitol", concepts.get("RxNorm", "456"));
  assertEquals("Examplotomy Encounter", concepts.get("SNOMED-CT", "ABC"));
  assertEquals("Examplotomy", concepts.get("SNOMED-CT", "789"));
}
项目:hadoop    文件:TestRefreshUserMappings.java   
private void addNewConfigResource(String rsrcName, String keyGroup,
    String groups, String keyHosts, String hosts)
        throws FileNotFoundException, UnsupportedEncodingException {
  // location for temp resource should be in CLASSPATH
  Configuration conf = new Configuration();
  URL url = conf.getResource("hdfs-site.xml");

  String urlPath = URLDecoder.decode(url.getPath().toString(), "UTF-8");
  Path p = new Path(urlPath);
  Path dir = p.getParent();
  tempResource = dir.toString() + "/" + rsrcName;

  String newResource =
  "<configuration>"+
  "<property><name>" + keyGroup + "</name><value>"+groups+"</value></property>" +
  "<property><name>" + keyHosts + "</name><value>"+hosts+"</value></property>" +
  "</configuration>";
  PrintWriter writer = new PrintWriter(new FileOutputStream(tempResource));
  writer.println(newResource);
  writer.close();

  Configuration.addDefaultResource(rsrcName);
}
项目:parabuild-ci    文件:IndexFiles.java   
public static void indexDocs(IndexWriter writer, File file)
  throws IOException {
  // do not try to index files that cannot be read
  if (file.canRead()) {
    if (file.isDirectory()) {
      String[] files = file.list();
      // an IO error could occur
      if (files != null) {
        for (int i = 0; i < files.length; i++) {
          indexDocs(writer, new File(file, files[i]));
        }
      }
    } else {
      System.out.println("adding " + file);
      try {
        writer.addDocument(FileDocument.Document(file));
      }
      // at least on windows, some temporary files raise this exception with an "access denied" message
      // checking if the file can be read doesn't help
      catch (FileNotFoundException fnfe) {
        ;
      }
    }
  }
}
项目:Myst    文件:MPCTestClient.java   
static void InsertPerfInfoIntoFiles(String basePath, String cardName, String experimentID, HashMap<Short, Pair<Short, Long>> perfResultsSubpartsRaw) throws FileNotFoundException, IOException {
    File dir = new File(basePath);
    String[] filesArray = dir.list();
    if ((filesArray != null) && (dir.isDirectory() == true)) {
        // make subdir for results
        String outputDir = String.format("%s\\perf\\%s\\", basePath, experimentID);
        new File(outputDir).mkdirs();

        for (String fileName : filesArray) {
            File dir2 = new File(basePath + fileName);
            if (!dir2.isDirectory()) {
                InsertPerfInfoIntoFile(String.format("%s\\%s", basePath, fileName), cardName, experimentID, outputDir, perfResultsSubpartsRaw);
            }
        }
    }
}
项目:appinventor-extensions    文件:ObjectifyStorageIo.java   
@Override
public byte[] downloadRawUserFile(final String userId, final String fileName) {
  final Result<byte[]> result = new Result<byte[]>();
  try {
    runJobWithRetries(new JobRetryHelper() {
      @Override
      public void run(Objectify datastore) {
        UserFileData ufd = datastore.find(userFileKey(userKey(userId), fileName));
        if (ufd != null) {
          result.t = ufd.content;
        } else {
          throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName),
              new FileNotFoundException(fileName));
        }
      }
    }, true);
  } catch (ObjectifyException e) {
    throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName), e);
  }
  return result.t;
}
项目:LightSIP    文件:NioTlsWebSocketMessageProcessor.java   
public void init() throws Exception, CertificateException, FileNotFoundException, IOException {
if(sipStack.securityManagerProvider.getKeyManagers(false) == null ||
        sipStack.securityManagerProvider.getTrustManagers(false) == null ||
              sipStack.securityManagerProvider.getTrustManagers(true) == null) {
    if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
              logger.logDebug("TLS initialization failed due to NULL security config");
          }
    return; // The settings 
}

      sslServerCtx = SSLContext.getInstance("TLS");
      sslServerCtx.init(sipStack.securityManagerProvider.getKeyManagers(false), 
              sipStack.securityManagerProvider.getTrustManagers(false),
              null);

      sslClientCtx = SSLContext.getInstance("TLS");
      sslClientCtx.init(sipStack.securityManagerProvider.getKeyManagers(true),
              sipStack.securityManagerProvider.getTrustManagers(true),
              null);

  }
项目:alerta-fraude    文件:FileUtils.java   
/**
 * Write contents of file.
 *
 * @param data              The contents of the file.
 * @param offset            The position to begin writing the file.
 * @param isBinary          True if the file contents are base64-encoded binary data
 */
/**/
public long write(String srcURLstr, String data, int offset, boolean isBinary) throws FileNotFoundException, IOException, NoModificationAllowedException {
    try {
        LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
        Filesystem fs = this.filesystemForURL(inputURL);
        if (fs == null) {
            throw new MalformedURLException("No installed handlers for this URL");
        }

        long x = fs.writeToFileAtURL(inputURL, data, offset, isBinary); LOG.d("TEST",srcURLstr + ": "+x); return x;
    } catch (IllegalArgumentException e) {
        MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
        mue.initCause(e);
        throw mue;
    }

}
项目:siiMobilityAppKit    文件:AssetFilesystem.java   
@Override
   public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
       String pathNoSlashes = inputURL.path.substring(1);
       if (pathNoSlashes.endsWith("/")) {
           pathNoSlashes = pathNoSlashes.substring(0, pathNoSlashes.length() - 1);
       }

       String[] files;
       try {
           files = listAssets(pathNoSlashes);
       } catch (IOException e) {
           FileNotFoundException fnfe = new FileNotFoundException();
           fnfe.initCause(e);
           throw fnfe;
       }

       LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length];
       for (int i = 0; i < files.length; ++i) {
           entries[i] = localUrlforFullPath(new File(inputURL.path, files[i]).getPath());
       }
       return entries;
}
项目:incubator-netbeans    文件:FileEncodingQueryDataEditorSupportTest.java   
public java.io.InputStream getInputStream () throws java.io.FileNotFoundException {
    if (openStreams < 0) {
        FileNotFoundException e = new FileNotFoundException("Already exists output stream");
        if (previousStream != null) {
            e.initCause(previousStream);
        }
        throw e;
    }

    class IS extends ByteArrayInputStream {
        public IS(byte[] arr) {
            super(arr);
            openStreams++;
        }

        @Override
        public void close() throws IOException {
            openStreams--;
            super.close();
        }
    }
    previousStream = new Exception("Input");

    return new IS(RUNNING.content.getBytes ());
}
项目:fuck_zookeeper    文件:RandomAccessFileReader.java   
public RandomAccessFileReader(File f) throws FileNotFoundException {
file = new RandomAccessFile(f, "r");
if (LOG.isDebugEnabled()) {
    try {
    LOG.debug("Opened file(" + f + ") with FD (" + file.getFD() + ")");
    } catch (IOException ioe) { 
    LOG.debug("Opened file(" + f + ") coulds get FD");
    }
}

buffer = new byte[DEFAULT_BUFFER_SIZE];
buffersize = 0;
bufferoffset = 0;
fileoffset = 0;
fp = 0;
   }
项目:ipack    文件:Packer.java   
public Packer(final File destFile,
              final Signer signer,
              final Boolean inPlace) throws FileNotFoundException {
    this.inPlace = inPlace;
    if (inPlace) { //In codesign.py this is what we use
        this.zipStream = new ZipOutputStream(
                             new DataOutputStream(
                                 new ByteArrayOutputStream(128*1024*1024-1))); //Avoid java bug https://bugs.openjdk.java.net/browse/JDK-8055949 by being able to get to max buffer size of MAX_INT-16
        zipStream.setLevel(Deflater.NO_COMPRESSION);
    } else {
        this.zipStream = new ZipOutputStream(
                             new BufferedOutputStream(
                                 new FileOutputStream(destFile)));
    }
    this.signer = signer;
}
项目:PCloud_Server_v3    文件:PropertiesHelper.java   
/**
 * 保存修改
 * @throws FileNotFoundException
 * @throws IOException
 */
public void save() throws FileNotFoundException, IOException {
    Properties prop = new Properties();
    if(fileName==null){
        throw new FileNotFoundException("Unspecified file name.");
    }
    FileOutputStream fos = new FileOutputStream(fileName);
    //遍历HashMap
    Iterator<Entry<String, String>> iter = hashMap.entrySet().iterator();
    while (iter.hasNext()) {
        Entry<String, String> entry = iter.next();
        prop.setProperty(entry.getKey(), entry.getValue());
    }
    //写入文件
    prop.store(fos, null);
    fos.close();
}
项目:alerta-fraude    文件:AssetFilesystem.java   
@Override
   public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
       String pathNoSlashes = inputURL.path.substring(1);
       if (pathNoSlashes.endsWith("/")) {
           pathNoSlashes = pathNoSlashes.substring(0, pathNoSlashes.length() - 1);
       }

       String[] files;
       try {
           files = listAssets(pathNoSlashes);
       } catch (IOException e) {
           FileNotFoundException fnfe = new FileNotFoundException();
           fnfe.initCause(e);
           throw fnfe;
       }

       LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length];
       for (int i = 0; i < files.length; ++i) {
           entries[i] = localUrlforFullPath(new File(inputURL.path, files[i]).getPath());
       }
       return entries;
}
项目:MOAAP    文件:PyramidActivity.java   
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch(requestCode) {
        case SELECT_PHOTO:
            if(resultCode == RESULT_OK){
                try {
                    final Uri imageUri = imageReturnedIntent.getData();
                    final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                    src = new Mat(selectedImage.getHeight(), selectedImage.getWidth(), CvType.CV_8UC4);
                    Utils.bitmapToMat(selectedImage, src);
                    srcSelected = true;
                    bGaussianPyrUp.setEnabled(true);
                    bGaussianPyrDown.setEnabled(true);
                    bLaplacianPyr.setEnabled(true);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            break;
    }
}
项目:incubator-netbeans    文件:WindowManagerParserTest.java   
/** Test of missing file
 */
public void testLoadWM01Invalid () throws Exception {
    System.out.println("");
    System.out.println("WindowManagerParserTest.testLoadWM01Invalid START");

    WindowManagerParser wmParser = createWMParser("data/invalid/Windows","windowmanager01");

    try {
        wmParser.load();
    } catch (FileNotFoundException exc) {
        //Missing file detected
        //ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, exc);
        System.out.println("WindowManagerParserTest.testLoadWM01Invalid FINISH");
        return;
    }

    fail("Missing file was not detected.");
}
项目:openaudible    文件:AudioFileIO.java   
/**
 * Check does file exist
 *
 * @param file
 * @throws java.io.FileNotFoundException
 */
public void checkFileExists(File file) throws FileNotFoundException {
    logger.config("Reading file:" + "path" + file.getPath() + ":abs:" + file.getAbsolutePath());
    if (!file.exists()) {
        logger.severe("Unable to find:" + file.getPath());
        throw new FileNotFoundException(ErrorMessage.UNABLE_TO_FIND_FILE.getMsg(file.getPath()));
    }
}
项目:Encryption    文件:BaseBuilder.java   
public B message(File file){
    try {
        return message(new FileInputStream(file));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    return null;
}
项目:devops-cstack    文件:FilesUtils.java   
/**
 * Untar
 * 
 * @throws IOException
 * @throws FileNotFoundException
 *
 * @return The {@link List} of {@link File}s with the untared content.
 * @throws ArchiveException
 */
public static void unTar(final InputStream is, final OutputStream outputFileStream)
        throws FileNotFoundException, IOException, ArchiveException {
    try {
        final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory()
                .createArchiveInputStream("tar", is);
        TarArchiveEntry entry = null;
        while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
            logger.debug("Entry = " + entry.getName());
            IOUtils.copy(debInputStream, outputFileStream);
        }
    } finally {
        is.close();
    }
}
项目:BUbiNG    文件:Agent.java   
@ManagedOperation @Description("Add a new IPv4 to the black list; it can be a single IP address or a file (prefixed by file:)")
public void addBlackListedIPv4(@org.softee.management.annotation.Parameter("address") @Description("An IPv4 address to be blacklisted") String address) throws ConfigurationException, FileNotFoundException {
    final Lock lock = rc.blackListedIPv4Lock.writeLock();
    lock.lock();
    try {
        rc.addBlackListedIPv4(address);
    } finally {
        lock.unlock();
    }
}
项目:virtualview_tools    文件:ViewCompiler.java   
private InputStream getFileInputStream(String fileName) {
    try {
        FileInputStream fis = new FileInputStream(fileName);
        return fis;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
项目:apache-tomcat-7.0.73-with-comment    文件:DirContextURLConnection.java   
/**
 * List children of this collection. The names given are relative to this
 * URI's path. The full uri of the children is then : path + "/" + name.
 */
public Enumeration<String> list()
    throws IOException {

    if (!connected) {
        connect();
    }

    if ((resource == null) && (collection == null)) {
        throw new FileNotFoundException(
                getURL() == null ? "null" : getURL().toString());
    }

    Vector<String> result = new Vector<String>();

    if (collection != null) {
        try {
            NamingEnumeration<NameClassPair> enumeration =
                collection.list("/");
            UEncoder urlEncoder = new UEncoder(UEncoder.SafeCharsSet.WITH_SLASH);
            while (enumeration.hasMoreElements()) {
                NameClassPair ncp = enumeration.nextElement();
                String s = ncp.getName();
                result.addElement(
                        urlEncoder.encodeURL(s, 0, s.length()).toString());
            }
        } catch (NamingException e) {
            // Unexpected exception
            throw new FileNotFoundException(
                    getURL() == null ? "null" : getURL().toString());
        }
    }

    return result.elements();

}
项目:RedisClusterManager    文件:SftpClient.java   
/** 
   * 上传文件 
   */  
  public void upload(String directory, File file) throws FileNotFoundException, SftpException {
    if(notify != null){
        notify.terminal("upload " + directory + "/" + file.getName());
}
    if(isExist(directory)){
        sftp.cd(directory);
    }else{
        mkdir(directory);
        sftp.cd(directory);
    }
      sftp.put(new FileInputStream(file), file.getName());  
  }
项目:Android-Demo_ImageCroper    文件:BitmapUtils.java   
/**
 * Decode image from uri using "inJustDecodeBounds" to get the image dimensions.
 */
private static BitmapFactory.Options decodeImageForOption(ContentResolver resolver, Uri uri) throws FileNotFoundException {
    InputStream stream = null;
    try {
        stream = resolver.openInputStream(uri);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(stream, EMPTY_RECT, options);
        options.inJustDecodeBounds = false;
        return options;
    } finally {
        closeSafe(stream);
    }
}
项目:hadoop    文件:HttpServer2.java   
/**
 * Get the pathname to the webapps files.
 * @param appName eg "secondary" or "datanode"
 * @return the pathname as a URL
 * @throws FileNotFoundException if 'webapps' directory cannot be found on CLASSPATH.
 */
protected String getWebAppsPath(String appName) throws FileNotFoundException {
  URL url = getClass().getClassLoader().getResource("webapps/" + appName);
  if (url == null)
    throw new FileNotFoundException("webapps/" + appName
        + " not found in CLASSPATH");
  String urlString = url.toString();
  return urlString.substring(0, urlString.lastIndexOf('/'));
}
项目:UHC    文件:UHC.java   
@Override
public void onPluginEnable() /* throws Exception - We ain't throwing shit. */ {
    instance = this;

    if (!getDataFolder().exists()) {
        getDataFolder().mkdirs();
    }

    try {
        mainConfig = gson.fromJson(new FileReader(getDataFolder().getAbsolutePath() + File.separatorChar +
                "config.json"), MainConfiguration.class);
    } catch (FileNotFoundException e) {
        getLogger().log(Level.INFO, "Setting up configs folder...");

        mainConfig = new MainConfiguration(
                false, 2000, 10, 120, 100,
                30, 20,
                1, 4, 0, 30,
                2, 12, 0, 90
        );
        MainConfigWriter.writeMainConfig(getDataFolder(), mainConfig);
    }

    rulesFile = new File(getDataFolder(), "rules.json");
    if (!rulesFile.exists()) {
        saveResource("rules.json", true);
    }

    Bukkit.getWorlds().forEach(world -> world.setGameRuleValue("NaturalRegeneration", "false")); // Make sure it's hardcore.

    new CommandHandler(this);
    Arrays.asList(new Listener[]{new DeathHandler(), new ArcheryHandler(), new GameInitializeHandler(), new JoinQuitHandlers(),
            new MessageHandler(), new HeadEatHandler(), new CraftingHandler()}).forEach(this::registerListener);
}
项目:hadoop    文件:PseudoLocalFs.java   
/**
 * Validate if the path provided is of expected format of Pseudo Local File
 * System based files.
 * @param path file path
 * @return the file size
 * @throws FileNotFoundException
 */
long validateFileNameFormat(Path path) throws FileNotFoundException {
  path = path.makeQualified(this);
  boolean valid = true;
  long fileSize = 0;
  if (!path.toUri().getScheme().equals(getUri().getScheme())) {
    valid = false;
  } else {
    String[] parts = path.toUri().getPath().split("\\.");
    try {
      fileSize = Long.parseLong(parts[parts.length - 1]);
      valid = (fileSize >= 0);
    } catch (NumberFormatException e) {
      valid = false;
    }
  }
  if (!valid) {
    throw new FileNotFoundException("File " + path
        + " does not exist in pseudo local file system");
  }
  return fileSize;
}
项目:gw4e.project    文件:ModelSearchPage.java   
private List<String> getModelPropertyNames() throws FileNotFoundException, CoreException, IOException {
    List<IProject> files = new ArrayList<IProject>();

    Stream<TableItem> stream = Arrays.stream(tableProjects.getItems());
    stream.filter(item -> item.getChecked()).map(item -> item.getData())
            .forEach(jp -> files.add(((IJavaProject) jp).getProject()));

    List<String> ret = GraphWalkerFacade.getPropertiesForGraphModels(files);
    if(ret!=null) ret.add(MessageUtil.getString("requirement_property"));
    return ret;
}
项目:FireFiles    文件:DocumentsProvider.java   
/**
 * Return a list of streamable MIME types matching the filter, which can be passed to
 * {@link #openTypedDocument(String, String, Bundle, CancellationSignal)}.
 *
 * <p>The default implementation returns a MIME type provided by
 * {@link #queryDocument(String, String[])} as long as it matches the filter and the document
 * does not have the {@link Document#FLAG_VIRTUAL_DOCUMENT} flag set.
 *
 * @see #getStreamTypes(Uri, String)
 * @see #openTypedDocument(String, String, Bundle, CancellationSignal)
 */
public String[] getDocumentStreamTypes(String documentId, String mimeTypeFilter) {
    Cursor cursor = null;
    try {
        cursor = queryDocument(documentId, null);
        if (cursor.moveToFirst()) {
            final String mimeType =
                cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_MIME_TYPE));
            final long flags =
                cursor.getLong(cursor.getColumnIndexOrThrow(Document.COLUMN_FLAGS));
            if ((flags & Document.FLAG_VIRTUAL_DOCUMENT) == 0 && mimeType != null &&
                    mimeTypeMatches(mimeTypeFilter, mimeType)) {
                return new String[] { mimeType };
            }
        }
    } catch (FileNotFoundException e) {
        return null;
    } finally {
        IoUtils.closeQuietly(cursor);
    }

    // No streamable MIME types.
    return null;
}
项目:circus-train    文件:CopyMapper.java   
/**
 * Implementation of the Mapper<>::map(). Does the copy.
 *
 * @param relPath The target path.
 * @param sourceFileStatus The source path.
 * @throws IOException
 */
@Override
public void map(Text relPath, CopyListingFileStatus sourceFileStatus, Context context)
  throws IOException, InterruptedException {
  Path sourcePath = sourceFileStatus.getPath();

  LOG.debug("S3MapReduceCp::map(): Received {}, {}", sourcePath, relPath);

  Path targetPath = new Path(targetFinalPath.toString() + relPath.toString());

  final String description = "Copying " + sourcePath + " to " + targetPath;
  context.setStatus(description);

  LOG.info(description);

  try {
    CopyListingFileStatus sourceCurrStatus;
    FileSystem sourceFS;
    try {
      sourceFS = sourcePath.getFileSystem(conf);
      sourceCurrStatus = new CopyListingFileStatus(sourceFS.getFileStatus(sourcePath));
    } catch (FileNotFoundException e) {
      throw new IOException(new RetriableFileCopyCommand.CopyReadException(e));
    }

    if (sourceCurrStatus.isDirectory()) {
      throw new RuntimeException("Copy listing must not contain directories. Found: " + sourceCurrStatus.getPath());
    }

    S3UploadDescriptor uploadDescriptor = describeUpload(sourceCurrStatus, targetPath);

    incrementCounter(context, Counter.BYTESEXPECTED, sourceFileStatus.getLen());
    long bytesCopied = copyFileWithRetry(description, context, sourceCurrStatus, uploadDescriptor);
    incrementCounter(context, Counter.BYTESCOPIED, bytesCopied);
    incrementCounter(context, Counter.COPY, 1L);

  } catch (IOException exception) {
    handleFailures(exception, sourceFileStatus, targetPath, context);
  }
}
项目:hadoop    文件:DistributedFileSystem.java   
private DirListingIterator(Path p, PathFilter filter,
    boolean needLocation) throws IOException {
  this.p = p;
  this.src = getPathName(p);
  this.filter = filter;
  this.needLocation = needLocation;
  // fetch the first batch of entries in the directory
  thisListing = dfs.listPaths(src, HdfsFileStatus.EMPTY_NAME,
      needLocation);
  statistics.incrementReadOps(1);
  if (thisListing == null) { // the directory does not exist
    throw new FileNotFoundException("File " + p + " does not exist.");
  }
  i = 0;
}
项目:DocIT    文件:Behavior.java   
@Test
public void testTotal() 
throws 
    JAXBException,
    FileNotFoundException,
    XMLStreamException 
{
    double total = Total.total(c);
    assertEquals(399747, total, 0);
}