java.nio.channels.ClosedByInterruptException#java.io.FileNotFoundException源码实例Demo

下面列出了java.nio.channels.ClosedByInterruptException#java.io.FileNotFoundException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: jstorm   文件: TestTopology.java
private static void LoadYaml(String confPath) {

		Yaml yaml = new Yaml();

		try {
			InputStream stream = new FileInputStream(confPath);

			conf = (Map) yaml.load(stream);
			if (conf == null || conf.isEmpty() == true) {
				throw new RuntimeException("Failed to read config file");
			}

		} catch (FileNotFoundException e) {
			System.out.println("No such file " + confPath);
			throw new RuntimeException("No config file");
		} catch (Exception e1) {
			e1.printStackTrace();
			throw new RuntimeException("Failed to read config file");
		}

		return;
	}
 
源代码2 项目: Pomfshare   文件: MainActivity.java
private void displayAndUpload(Host host) {
	ContentResolver cr = getContentResolver();
	if (imageUri != null) {
		ImageView view = (ImageView)findViewById(R.id.sharedImageView);
		view.setImageURI(imageUri);

		ParcelFileDescriptor inputPFD = null; 
		try {
			inputPFD = cr.openFileDescriptor(imageUri, "r");				
		} catch (FileNotFoundException e) {
			Log.e(tag, e.getMessage());
			Toast toast = Toast.makeText(getApplicationContext(), "Unable to read file.", Toast.LENGTH_SHORT);
			toast.show();				
		}

		new Uploader(this, inputPFD, host).execute(imageUri.getLastPathSegment(), cr.getType(imageUri));
	}
}
 
源代码3 项目: mmtf-spark   文件: ReadMmtfReduced.java
public static void main(String[] args) throws FileNotFoundException {  
	
	String path = MmtfReader.getMmtfReducedPath();
    
    // instantiate Spark. Each Spark application needs these two lines of code.
    SparkConf conf = new SparkConf().setMaster("local[*]").setAppName(ReadMmtfReduced.class.getSimpleName());
    JavaSparkContext sc = new JavaSparkContext(conf);
	 
    // read list of PDB entries from a local Hadoop sequence file
    List<String> pdbIds = Arrays.asList("1AQ1","1B38","1B39","1BUH"); 
    JavaPairRDD<String, StructureDataInterface> pdb = MmtfReader.readSequenceFile(path, pdbIds, sc);
    
    System.out.println("# structures: " + pdb.count());
    
    // close Spark
    sc.close();
}
 
private static ProcessEngine getOrInitializeCachedProcessEngine() {
  if (cachedProcessEngine == null) {
    try {
      cachedProcessEngine = ProcessEngineConfiguration
              .createProcessEngineConfigurationFromResource("camunda.cfg.xml")
              .buildProcessEngine();
    } catch (RuntimeException ex) {
      if (ex.getCause() != null && ex.getCause() instanceof FileNotFoundException) {
        cachedProcessEngine = ProcessEngineConfiguration
            .createProcessEngineConfigurationFromResource("activiti.cfg.xml")
            .buildProcessEngine();
      } else {
        throw ex;
      }
    }
  }
  return cachedProcessEngine;
}
 
源代码5 项目: droid-stealth   文件: LocalStorageProvider.java
private void includeFile(final MatrixCursor result, final File file)
        throws FileNotFoundException {
    final MatrixCursor.RowBuilder row = result.newRow();
    // These columns are required
    row.add(Document.COLUMN_DOCUMENT_ID, file.getAbsolutePath());
    row.add(Document.COLUMN_DISPLAY_NAME, file.getName());
    String mimeType = getDocumentType(file.getAbsolutePath());
    row.add(Document.COLUMN_MIME_TYPE, mimeType);
    int flags = file.canWrite() ? Document.FLAG_SUPPORTS_DELETE | Document.FLAG_SUPPORTS_WRITE
            : 0;
    // We only show thumbnails for image files - expect a call to
    // openDocumentThumbnail for each file that has
    // this flag set
    if (mimeType.startsWith("image/"))
        flags |= Document.FLAG_SUPPORTS_THUMBNAIL;
    row.add(Document.COLUMN_FLAGS, flags);
    // COLUMN_SIZE is required, but can be null
    row.add(Document.COLUMN_SIZE, file.length());
    // These columns are optional
    row.add(Document.COLUMN_LAST_MODIFIED, file.lastModified());
    // Document.COLUMN_ICON can be a resource id identifying a custom icon.
    // The system provides default icons
    // based on mime type
    // Document.COLUMN_SUMMARY is optional additional information about the
    // file
}
 
源代码6 项目: java-sdk   文件: SpeechToTextTest.java
/**
 * Test train language model.
 *
 * @throws InterruptedException the interrupted exception
 * @throws FileNotFoundException the file not found exception
 */
@Test
public void testTrainLanguageModel() throws InterruptedException, FileNotFoundException {
  server.enqueue(
      new MockResponse().addHeader(CONTENT_TYPE, HttpMediaType.APPLICATION_JSON).setBody("{}"));
  String id = "foo";

  TrainLanguageModelOptions trainOptions =
      new TrainLanguageModelOptions.Builder()
          .customizationId(id)
          .wordTypeToAdd(TrainLanguageModelOptions.WordTypeToAdd.ALL)
          .customizationWeight(0.5)
          .build();
  service.trainLanguageModel(trainOptions).execute().getResult();
  final RecordedRequest request = server.takeRequest();

  assertEquals("POST", request.getMethod());
  assertEquals(
      String.format(PATH_TRAIN, id) + "?word_type_to_add=all&customization_weight=" + 0.5,
      request.getPath());
}
 
源代码7 项目: commons-vfs   文件: UrlFileObject.java
/**
 * Determines the type of the file.
 */
@Override
protected FileType doGetType() throws Exception {
    try {
        // Attempt to connect & check status
        final URLConnection conn = url.openConnection();
        final InputStream in = conn.getInputStream();
        try {
            if (conn instanceof HttpURLConnection) {
                final int status = ((HttpURLConnection) conn).getResponseCode();
                // 200 is good, maybe add more later...
                if (HttpURLConnection.HTTP_OK != status) {
                    return FileType.IMAGINARY;
                }
            }

            return FileType.FILE;
        } finally {
            in.close();
        }
    } catch (final FileNotFoundException e) {
        return FileType.IMAGINARY;
    }
}
 
源代码8 项目: athenz   文件: CryptoExceptionTest.java
@Test
public void testCryptoExceptions() {

    CryptoException ex = new CryptoException();
    assertNotNull(ex);
    assertEquals(ex.getCode(), CryptoException.CRYPTO_ERROR);

    assertNotNull(new CryptoException(new NoSuchAlgorithmException()));
    assertNotNull(new CryptoException(new InvalidKeyException()));
    assertNotNull(new CryptoException(new NoSuchProviderException()));
    assertNotNull(new CryptoException(new SignatureException()));
    assertNotNull(new CryptoException(new FileNotFoundException()));
    assertNotNull(new CryptoException(new IOException()));
    assertNotNull(new CryptoException(new CertificateException()));
    assertNotNull(new CryptoException(new InvalidKeySpecException()));
    assertNotNull(new CryptoException(new OperatorCreationException("unit-test")));
    assertNotNull(new CryptoException(new PKCSException("unit-test")));
    assertNotNull(new CryptoException(new CMSException("unit-test")));

    ex = new CryptoException(CryptoException.CERT_HASH_MISMATCH, "X.509 Certificate hash mismatch");
    assertEquals(ex.getCode(), CryptoException.CERT_HASH_MISMATCH);
}
 
源代码9 项目: lams   文件: ClassPathResource.java
/**
 * This implementation opens an InputStream for the given class path resource.
 * @see java.lang.ClassLoader#getResourceAsStream(String)
 * @see java.lang.Class#getResourceAsStream(String)
 */
@Override
public InputStream getInputStream() throws IOException {
	InputStream is;
	if (this.clazz != null) {
		is = this.clazz.getResourceAsStream(this.path);
	}
	else if (this.classLoader != null) {
		is = this.classLoader.getResourceAsStream(this.path);
	}
	else {
		is = ClassLoader.getSystemResourceAsStream(this.path);
	}
	if (is == null) {
		throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
	}
	return is;
}
 
源代码10 项目: iBeebo   文件: ImgsActivity.java
@Override
public void OnItemClick(View v, int Position, CheckBox checkBox) {
    String filapath = fileTraversal.filecontent.get(Position);
    if (checkBox.isChecked()) {
        checkBox.setChecked(false);
        mSendImgData.removeSendImg(filapath);
    } else {
        try {
            if (mSendImgData.getSendImgs().size() >= 1) {
                Toast.makeText(getApplicationContext(), R.string.send_tomanay_pics, Toast.LENGTH_SHORT).show();
            } else {
                checkBox.setChecked(true);
                Log.i("img", "img choise position->" + Position);
                ImageView imageView = iconImage(filapath, Position, checkBox);
                if (imageView != null) {
                    hashImage.put(Position, imageView);
                    mSendImgData.addSendImg(filapath);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    updateCount(mMenuItem);
}
 
源代码11 项目: MediaSDK   文件: DownloadExceptionUtils.java
public static int getErrorCode(Throwable e) {
    if (e instanceof SocketTimeoutException) {
        return SOCKET_TIMEOUT_ERROR;
    } else if (e instanceof FileNotFoundException) {
        return FILE_NOT_FOUND_ERROR;
    } else if (e instanceof VideoCacheException) {
        if (((VideoCacheException) e).getMsg().equals(FILE_LENGTH_FETCHED_ERROR_STRING)) {
            return FILE_LENGTH_FETCHED_ERROR;
        } else if (((VideoCacheException) e).getMsg().equals(M3U8_FILE_CONTENT_ERROR_STRING)) {
            return M3U8_FILE_CONTENT_ERROR;
        } else if (((VideoCacheException) e).getMsg().equals(MIMETYPE_NULL_ERROR_STRING)) {
            return MIMETYPE_NULL_ERROR;
        } else if(((VideoCacheException) e).getMsg().equals(MIMETYPE_NOT_FOUND_STRING)) {

        }
    } else if (e instanceof UnknownHostException) {
        return UNKNOWN_HOST_ERROR;
    }
    return UNKNOWN_ERROR;
}
 
源代码12 项目: mollyim-android   文件: MmsBodyProvider.java
@Override
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException {
  Log.i(TAG, "openFile(" + uri + ", " + mode + ")");

  switch (uriMatcher.match(uri)) {
  case SINGLE_ROW:
    Log.i(TAG, "Fetching message body for a single row...");
    File tmpFile = getFile(uri);

    final int fileMode;
    switch (mode) {
    case "w": fileMode = ParcelFileDescriptor.MODE_TRUNCATE |
                         ParcelFileDescriptor.MODE_CREATE   |
                         ParcelFileDescriptor.MODE_WRITE_ONLY; break;
    case "r": fileMode = ParcelFileDescriptor.MODE_READ_ONLY;  break;
    default:  throw new IllegalArgumentException("requested file mode unsupported");
    }

    Log.i(TAG, "returning file " + tmpFile.getAbsolutePath());
    return ParcelFileDescriptor.open(tmpFile, fileMode);
  }

  throw new FileNotFoundException("Request for bad message.");
}
 
private static void buildVitalSignsSet() throws FileNotFoundException, IOException, FHIRFormatError {
  Calendar base = Calendar.getInstance();
  base.add(Calendar.DAY_OF_MONTH, -1);
  Bundle b = new Bundle();
  b.setType(BundleType.COLLECTION);
  b.setId(UUID.randomUUID().toString().toLowerCase());
  
  vitals(b, base, 0, 80, 120, 95, 37.1);
  vitals(b, base, 35, 85, 140, 98, 36.9);
  vitals(b, base, 53, 75, 110, 96, 36.2);
  vitals(b, base, 59, 65, 100, 94, 35.5);
  vitals(b, base, 104, 60, 90, 90, 35.9);
  vitals(b, base, 109, 65, 100, 92, 36.5);
  vitals(b, base, 114, 70, 130, 94, 37.5);
  vitals(b, base, 120, 90, 150, 97, 37.3);
  vitals(b, base, 130, 95, 133, 97, 37.2);
  vitals(b, base, 150, 85, 125, 98, 37.1);
  
  new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream("c:\\temp\\vitals.xml"), b);
}
 
源代码14 项目: maxent_iis   文件: DataSet.java
/**
 * ��ȡ���ݼ�
 * @param path
 * @return
 * @throws FileNotFoundException
 */
public static List<Instance> readDataSet(String path) throws FileNotFoundException
{
    File file = new File(path);
    Scanner scanner = new Scanner(file);
    List<Instance> instances = new ArrayList<Instance>();

    while (scanner.hasNextLine())
    {
        String line = scanner.nextLine();
        List<String> tokens = Arrays.asList(line.split("\\s"));
        String s1 = tokens.get(0);
        int label = Integer.parseInt(s1.substring(s1.length() - 1));
        int[] features = new int[tokens.size() - 1];

        for (int i = 1; i < tokens.size(); i++)
        {
            String s = tokens.get(i);
            features[i - 1] = Integer.parseInt(s.substring(s.length() - 1));
        }
        Instance instance = new Instance(label, features);
        instances.add(instance);
    }
    scanner.close();
    return instances;
}
 
源代码15 项目: ache   文件: TargetStorageMonitor.java
public static HashSet<String> readRelevantUrls(String dataPath) {
    String fileRelevantPages = dataPath + "/data_monitor/relevantpages.csv";
    HashSet<String> relevantUrls = new HashSet<>();
    try(Scanner scanner = new Scanner(new File(fileRelevantPages))) {
        while(scanner.hasNext()){
            String nextLine = scanner.nextLine();
            String[] splittedLine = nextLine.split("\t");
            if(splittedLine.length == 3) {
                String url = splittedLine[0];
                relevantUrls.add(url);
            }
        }
        return relevantUrls;
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Failed to load relevant URL from target monitor file: "+fileRelevantPages);
    }
}
 
源代码16 项目: q   文件: BaseIndexer.java
public Map<String, String> getTitleToIds() throws FileNotFoundException, UnsupportedEncodingException, IOException
 {
     Map<String, String> titleIdToName = Maps.newHashMap();

     InputStream is = new BufferedInputStream(new FileInputStream(inputFileName), BUFFER_SIZE);
     BufferedReader reader = new BufferedReader(new InputStreamReader(is, ENCODING), BUFFER_SIZE);
     String lineString = null;
     while ((lineString = reader.readLine()) != null) {
String[] line = lineString.split(Properties.inputDelimiter.get());
String id = line[0];
titleIdToName.put(StringUtils.createIdUsingTestName(id, testName), line[2]);
     }
     reader.close();
     is.close();
     return titleIdToName;
 }
 
源代码17 项目: BIMserver   文件: Express2EMF.java
public Express2EMF(File schemaFileName, String modelName, String nsUri) {
	schema = new SchemaLoader(schemaFileName.getAbsolutePath()).getSchema();
	eFactory = EcoreFactory.eINSTANCE;
	ePackage = EcorePackage.eINSTANCE;
	schemaPack = eFactory.createEPackage();
	try {
		new DerivedReader(schemaFileName, schema);
	} catch (FileNotFoundException e) {
		LOGGER.error("", e);
	}
	schemaPack.setName(modelName);
	schemaPack.setNsPrefix("iai");
	schemaPack.setNsURI(nsUri);

	createTristate();

	addClasses();
	addSupertypes();
	addSimpleTypes();
	addDerivedTypes();
	addEnumerations();
	addHackedTypes();
	addSelects();
	addAttributes();
	addInverses();
	EClass ifcBooleanClass = (EClass) schemaPack.getEClassifier("IfcBoolean");
	ifcBooleanClass.getESuperTypes().add((EClass) schemaPack.getEClassifier("IfcValue"));
	doRealDerivedAttributes();
	clean();
}
 
源代码18 项目: yago3   文件: Theme.java
/** Assigns the theme to a file (to use data that is already there) */
public synchronized Theme assignToFolder(File folder) throws IOException {
  File f = findFileInFolder(folder);
  if (f == null) throw new FileNotFoundException("Cannot find theme " + this + " in " + folder.getCanonicalPath());
  if (file != null) {
    if (file.equals(f)) return (this);
    else throw new IOException("Theme " + this + " is already assigned to file " + file + ", cannot assign it to " + f);
  }
  file = f;
  cache = null;
  return (this);
}
 
源代码19 项目: dremio-oss   文件: DremioHadoopFileSystemWrapper.java
@Override
public DirectoryStream<FileAttributes> list(Path f) throws FileNotFoundException, IOException {
  try (WaitRecorder recorder = OperatorStats.getWaitRecorder(operatorStats)) {
    return new ArrayDirectoryStream(underlyingFs.listStatus(toHadoopPath(f)));
  } catch(FSError e) {
    throw propagateFSError(e);
  }
}
 
源代码20 项目: FireFiles   文件: DocumentsContractApi19.java
public static boolean delete(Context context, Uri self) {
    try {
        return DocumentsContract.deleteDocument(context.getContentResolver(), self);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    }
}
 
源代码21 项目: openjdk-jdk8u-backup   文件: Gen.java
private void writeIfChanged(byte[] b, FileObject file) throws IOException {
    boolean mustWrite = false;
    String event = "[No need to update file ";

    if (force) {
        mustWrite = true;
        event = "[Forcefully writing file ";
    } else {
        InputStream in;
        byte[] a;
        try {
            // regrettably, there's no API to get the length in bytes
            // for a FileObject, so we can't short-circuit reading the
            // file here
            in = file.openInputStream();
            a = readBytes(in);
            if (!Arrays.equals(a, b)) {
                mustWrite = true;
                event = "[Overwriting file ";

            }
        } catch (FileNotFoundException e) {
            mustWrite = true;
            event = "[Creating file ";
        }
    }

    if (util.verbose)
        util.log(event + file + "]");

    if (mustWrite) {
        OutputStream out = file.openOutputStream();
        out.write(b); /* No buffering, just one big write! */
        out.close();
    }
}
 
源代码22 项目: ache   文件: FileSystemTargetRepository.java
private <T> T readFile(Path filePath) throws IOException, FileNotFoundException {
    if (!Files.exists(filePath)) {
        return null;
    }
    try (InputStream fileStream = new FileInputStream(filePath.toFile())) {
        if(compressData) {
            try(InputStream gzipStream = new InflaterInputStream(fileStream)) {
                return unserializeData(gzipStream);
            }
        } else {
            return unserializeData(fileStream);
        }
    }
}
 
源代码23 项目: Lottery   文件: DistributeJob.java
/**
 * 分发文件夹到指定FTP
 */
public void distribute() throws FileNotFoundException, IOException {
	Ftp ftp=ftpMng.findById(ftpId);
	for(String folder:this.folders){
		log.info("distribute folder  "+folder);
		String folderPath=realPathResolver.get(folder);
		String rootPath=realPathResolver.get("");
		if(StringUtils.isNotBlank(folder)&&StringUtils.isNotBlank(folderPath)){
			ftp.storeByFloder(folderPath,rootPath);
		}
	}
}
 
源代码24 项目: jdk8u_jdk   文件: FtpURLConnectionLeak.java
public static void main(String[] args) throws Exception {
    FtpServer server = new FtpServer(0);
    server.setFileSystemHandler(new CustomFileSystemHandler("/"));
    server.setAuthHandler(new MyAuthHandler());
    int port = server.getLocalPort();
    server.start();
    URL url = new URL("ftp://localhost:" + port + "/filedoesNotExist.txt");
    for (int i = 0; i < 3; i++) {
        try {
            InputStream stream = url.openStream();
        } catch (FileNotFoundException expectedFirstTimeAround) {
            // should always reach this point since the path does not exist
        } catch (IOException expected) {
            System.out.println("caught expected " + expected);
            int times = 1;
            do {
                // give some time to close the connection...
                System.out.println("sleeping... " + times);
                Thread.sleep(times * 1000);
            } while (server.activeClientsCount() > 0 && times++ < 5);

            if (server.activeClientsCount() > 0) {
                server.killClients();
                throw new RuntimeException("URLConnection didn't close the" +
                        " FTP connection on FileNotFoundException");
            }
        } finally {
            server.terminate();
        }
    }
}
 
源代码25 项目: http4e   文件: BusinessJob.java
private void addMultipart_Parts( MultipartPostMethod method, Map<String, String> parameterizedMap){
   for (Iterator it = model.getParameters().entrySet().iterator(); it.hasNext();) {
      Map.Entry me = (Map.Entry) it.next();
      String key = (String) me.getKey();
      List values = (List) me.getValue();
      StringBuilder sb = new StringBuilder();
      int cnt = 0;
      for (Iterator it2 = values.iterator(); it2.hasNext();) {
         String val = (String) it2.next();
         if (cnt != 0) {
            sb.append(",");
         }
         sb.append(val);
         cnt++;
      }

      String parameterizedVal = ParseUtils.getParametizedArg(sb.toString(), parameterizedMap);

      if (parameterizedVal.startsWith("@")) {
         String path = "";
         String contentType = "";
         try {
            path = parameterizedVal.substring(1, parameterizedVal.length()).trim();
            path = path.replace('\\', '/');
            contentType = getContentType(getFileExt(path));
            File f = new File(path);
            method.addPart(new FilePart(key, f, contentType, null));
            // postMethod.addParameter("file", f);
            // postMethod.addPart(new FilePart("file", f));
         } catch (FileNotFoundException fnfe) {
            ExceptionHandler.handle(fnfe);
         }

      } else {
         method.addPart(new StringPart(key, parameterizedVal));

      }
   }
}
 
源代码26 项目: drftpd   文件: DirectoryHandle.java
/**
 * @param reason
 * @throws FileNotFoundException if this Directory does not exist
 */
public void abortAllTransfers(String reason) throws FileNotFoundException {
    for (FileHandle file : getFilesUnchecked()) {
        try {
            file.abortTransfers(reason);
        } catch (FileNotFoundException e) {
        }
    }
}
 
源代码27 项目: tus-java-client   文件: TusUpload.java
/**
 * Create a new TusUpload object using the supplied File object. The corresponding {@link
 * InputStream}, size and fingerprint will be automatically set.
 *
 * @param file The file whose content should be later uploaded.
 * @throws FileNotFoundException Thrown if the file cannot be found.
 */
public TusUpload(@NotNull File file) throws FileNotFoundException {
    size = file.length();
    setInputStream(new FileInputStream(file));

    fingerprint = String.format("%s-%d", file.getAbsolutePath(), size);

    metadata = new HashMap<String, String>();
    metadata.put("filename", file.getName());
}
 
源代码28 项目: sakai   文件: SakaiMessageHandlerTest.java
public void writeData(SmartClient client, String resource) throws IOException {
    client.dataStart();
    InputStream is = getClass().getResourceAsStream(resource);
    if(is == null) {
        throw new FileNotFoundException("Couldn't find in classpath: "+ resource);
    }
    byte[] bytes = IOUtils.toByteArray(is);
    client.dataWrite(bytes, bytes.length);
    client.dataEnd();
}
 
@Test
public void writeContentNotGettingInputStream() throws Exception {
	Resource resource = mock(Resource.class);
	given(resource.getInputStream()).willThrow(FileNotFoundException.class);

	this.handler.writeContent(this.response, resource);

	assertEquals(200, this.response.getStatus());
	assertEquals(0, this.response.getContentLength());
}
 
@Override
@Nullable
public InputSource resolveEntity(String publicId, @Nullable String systemId) throws IOException {
	if (logger.isTraceEnabled()) {
		logger.trace("Trying to resolve XML entity with public id [" + publicId +
				"] and system id [" + systemId + "]");
	}

	if (systemId != null) {
		String resourceLocation = getSchemaMappings().get(systemId);
		if (resourceLocation != null) {
			Resource resource = new ClassPathResource(resourceLocation, this.classLoader);
			try {
				InputSource source = new InputSource(resource.getInputStream());
				source.setPublicId(publicId);
				source.setSystemId(systemId);
				if (logger.isTraceEnabled()) {
					logger.trace("Found XML schema [" + systemId + "] in classpath: " + resourceLocation);
				}
				return source;
			}
			catch (FileNotFoundException ex) {
				if (logger.isDebugEnabled()) {
					logger.debug("Could not find XML schema [" + systemId + "]: " + resource, ex);
				}
			}
		}
	}
	return null;
}