Java Code Examples for java.io.FileInputStream

The following examples show how to use java.io.FileInputStream. These examples are extracted from open source projects.
Example 1
Project: openjdk-jdk8u-backup   File: GetORBPropertiesFileAction.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void getPropertiesFromFile( Properties props, String fileName )
{
    try {
        File file = new File( fileName ) ;
        if (!file.exists())
            return ;

        FileInputStream in = new FileInputStream( file ) ;

        try {
            props.load( in ) ;
        } finally {
            in.close() ;
        }
    } catch (Exception exc) {
        if (debug)
            System.out.println( "ORB properties file " + fileName +
                " not found: " + exc) ;
    }
}
 
Example 2
Project: verigreen   File: TestCollectorE2EGreenPath.java    License: Apache License 2.0 6 votes vote down vote up
/**
    * 
    * Change the job name in the config.properties file
    * */
   public void changeConfigFileJobName(String job) throws IOException
   {

   	InputStream input = new FileInputStream(_path);

       BufferedReader reader = new BufferedReader(new InputStreamReader(input));
       StringBuilder out = new StringBuilder();
       String line, row = null;
	while ((line = reader.readLine()) != null) {
		row = line.toString();
		if(line.toString().contains("jenkins.jobName")){
			row = "jenkins.jobName=" + job;
		}
		out.append(row + "\n");
       }
       reader.close();
      
       OutputStream output = new FileOutputStream(_path);

	BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
	writer.write(out.toString());
   	writer.close();
}
 
Example 3
Project: biojava   File: DemoMmcifToPdbConverter.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void convert(File inFile, File outFile) throws IOException {

	MMcifParser parser = new SimpleMMcifParser();

	SimpleMMcifConsumer consumer = new SimpleMMcifConsumer();
	parser.addMMcifConsumer(consumer);
	parser.parse(new BufferedReader(new InputStreamReader(new FileInputStream(inFile))));

	// now get the protein structure.
	Structure cifStructure = consumer.getStructure();

	// and write it out as PDB format
	PrintWriter pr = new PrintWriter(outFile);
	for (Chain c : cifStructure.getChains()) {
			// we can override the chain name, the mmCIF chain names might have more than 1 character
			c.setName(c.getName().substring(0, 1));
			pr.print(c.toPDB());
			pr.println("TER");
	}

		pr.close();


	}
 
Example 4
Project: tablesaw   File: SawReader.java    License: Apache License 2.0 6 votes vote down vote up
/** Reads the TextColumn data from the given file and stuffs it into a new TextColumn */
private static TextColumn readTextColumn(
    String fileName, TableMetadata tableMetadata, ColumnMetadata columnMetadata)
    throws IOException {

  TextColumn textColumn = TextColumn.create(columnMetadata.getName());
  try (FileInputStream fis = new FileInputStream(fileName);
      SnappyFramedInputStream sis = new SnappyFramedInputStream(fis, true);
      DataInputStream dis = new DataInputStream(sis)) {

    int j = 0;
    while (j < tableMetadata.getRowCount()) {
      textColumn.append(dis.readUTF());
      j++;
    }
  }
  return textColumn;
}
 
Example 5
Project: translationstudio8   File: ZipUtil.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 将压缩文件中的内容解压到指定目录中<br>
 * 如果<code>baseDir</code>的值为空,则将文件解压到相同的目录中,目录名称为"zipFile_files"
 * @param zipFile
 *            压缩文件路径
 * @param baseDir
 *            解压的目标路径,可以为null
 * @throws IOException
 */
public static String upZipFile(String zipFile, String baseDir) throws IOException {
	File f = new File(zipFile);
	if (baseDir == null) {
		baseDir = f.getPath() + "_files";
	}
	ZipInputStream zis = new ZipInputStream(new FileInputStream(f));
	ZipEntry ze;
	byte[] buf = new byte[1024];
	while ((ze = zis.getNextEntry()) != null) {
		File outFile = getRealFileName(baseDir, ze.getName());
		FileOutputStream os = new FileOutputStream(outFile);
		int readLen = 0;
		while ((readLen = zis.read(buf, 0, 1024)) != -1) {
			os.write(buf, 0, readLen);
		}
		os.close();
	}
	zis.close();
	return baseDir;
}
 
Example 6
Project: product-microgateway   File: ProtobufParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Compile the protobuf and generate descriptor file.
 *
 * @param protoPath      protobuf file path
 * @param descriptorPath descriptor file path
 * @return {@link DescriptorProtos.FileDescriptorSet} object
 */
private static DescriptorProtos.FileDescriptorProto generateRootFileDescriptor(String protoPath,
                                                                              String descriptorPath) {
    String command = new ProtocCommandBuilder
            (protoPath, resolveProtoFolderPath(protoPath), descriptorPath).build();
    generateDescriptor(command);
    File initialFile = new File(descriptorPath);
    try (InputStream targetStream = new FileInputStream(initialFile)) {
        ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
        //to register all custom extensions in order to parse properly
        ExtensionHolder.registerAllExtensions(extensionRegistry);
        DescriptorProtos.FileDescriptorSet set = DescriptorProtos.FileDescriptorSet.parseFrom(targetStream,
                extensionRegistry);
        logger.debug("Descriptor file is parsed successfully. file:" , descriptorPath);
        if (set.getFileList().size() > 0) {
            return set.getFile(0);
        }
    } catch (IOException e) {
        throw new CLIInternalException("Error reading generated descriptor file '" + descriptorPath + "'.", e);
    }
    return null;
}
 
Example 7
Project: hadoop   File: TestSlive.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDataWriting() throws Exception {
  long byteAm = 100;
  File fn = getTestFile();
  DataWriter writer = new DataWriter(rnd);
  FileOutputStream fs = new FileOutputStream(fn);
  GenerateOutput ostat = writer.writeSegment(byteAm, fs);
  LOG.info(ostat);
  fs.close();
  assertTrue(ostat.getBytesWritten() == byteAm);
  DataVerifier vf = new DataVerifier();
  FileInputStream fin = new FileInputStream(fn);
  VerifyOutput vfout = vf.verifyFile(byteAm, new DataInputStream(fin));
  LOG.info(vfout);
  fin.close();
  assertEquals(vfout.getBytesRead(), byteAm);
  assertTrue(vfout.getChunksDifferent() == 0);
}
 
Example 8
Project: micro-integrator   File: SampleAxis2Server.java    License: Apache License 2.0 6 votes vote down vote up
private File copyServiceToFileSystem(String resourceName, String fileName) throws IOException {
    File file = new File(System.getProperty("basedir") + File.separator + "target" + File.separator + fileName);
    if (file.exists()) {
        FileUtils.deleteQuietly(file);
    }

    FileUtils.touch(file);
    OutputStream os = FileUtils.openOutputStream(file);

    InputStream is = new FileInputStream(
            FrameworkPathUtil.getSystemResourceLocation() + File.separator + "artifacts" + File.separator + "AXIS2"
                    + File.separator + "config" + File.separator + resourceName);
    if (is != null) {
        byte[] data = new byte[1024];
        int len;
        while ((len = is.read(data)) != -1) {
            os.write(data, 0, len);
        }
        os.flush();
        os.close();
        is.close();
    }
    return file;
}
 
Example 9
Project: fosstrak-epcis   File: CaptureOperationsServlet.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Loads the application properties and populates a java.util.Properties
 * instance.
 * 
 * @param servletConfig
 *            The ServletConfig used to locate the application property
 *            file.
 * @return The application properties.
 */
private Properties loadApplicationProperties(ServletConfig servletConfig) {
    // read application properties from servlet context
    ServletContext ctx = servletConfig.getServletContext();
    String path = ctx.getRealPath("/");
    String appConfigFile = ctx.getInitParameter(APP_CONFIG_LOCATION);
    Properties properties = new Properties();
    try {
        InputStream is = new FileInputStream(path + appConfigFile);
        properties.load(is);
        is.close();
        LOG.info("Loaded application properties from " + path + appConfigFile);
    } catch (IOException e) {
        LOG.error("Unable to load application properties from " + path + appConfigFile, e);
    }
    return properties;
}
 
Example 10
Project: candybar   File: DiskLruCache.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns an unbuffered input stream to read the last committed value,
 * or null if no value has been committed.
 */
public InputStream newInputStream(int index) throws IOException {
    synchronized (DiskLruCache.this) {
        if (entry.currentEditor != this) {
            throw new IllegalStateException();
        }
        if (!entry.readable) {
            return null;
        }
        try {
            return new FileInputStream(entry.getCleanFile(index));
        } catch (FileNotFoundException e) {
            return null;
        }
    }
}
 
Example 11
Project: jdk8u-jdk   File: Main.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Given a file, find only the properties that are setable by AppletViewer.
 *
 * @param inFile A Properties file from which we select the properties of
 *             interest.
 * @return     A Properties object containing all of the AppletViewer
 *             user-specific properties.
 */
private Properties getAVProps(File inFile) {
    Properties avProps  = new Properties();

    // read the file
    Properties tmpProps = new Properties();
    try (FileInputStream in = new FileInputStream(inFile)) {
        tmpProps.load(new BufferedInputStream(in));
    } catch (IOException e) {
        System.err.println(lookup("main.err.prop.cantread", inFile.toString()));
    }

    // pick off the properties we care about
    for (int i = 0; i < avDefaultUserProps.length; i++) {
        String value = tmpProps.getProperty(avDefaultUserProps[i][0]);
        if (value != null) {
            // the property exists in the file, so replace the default
            avProps.setProperty(avDefaultUserProps[i][0], value);
        } else {
            // just use the default
            avProps.setProperty(avDefaultUserProps[i][0],
                                avDefaultUserProps[i][1]);
        }
    }
    return avProps;
}
 
Example 12
Project: game-server   File: FileUtil.java    License: MIT License 6 votes vote down vote up
public static String readTxtFile(String filePath) {
    try {
        String encoding = "UTF-8";
        File file = new File(filePath);
        if (file.isFile() && file.exists()) { //判断文件是否存在
            InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file), encoding);//考虑到编码格式
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;
            StringBuffer sb = new StringBuffer();
            while ((lineTxt = bufferedReader.readLine()) != null) {
                sb.append(lineTxt).append("\n");
            }
            read.close();
            return sb.toString();
        } else {
            log.warn("文件{}配置有误,找不到指定的文件", file);
        }
    } catch (Exception e) {
        log.error("读取文件内容出错", e);
    }
    return null;
}
 
Example 13
Project: mxisd   File: YamlConfigLoader.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public static MxisdConfig loadFromFile(String path) throws IOException {
    File f = new File(path).getAbsoluteFile();
    log.info("Reading config from {}", f.toString());
    Representer rep = new Representer();
    rep.getPropertyUtils().setBeanAccess(BeanAccess.FIELD);
    rep.getPropertyUtils().setAllowReadOnlyProperties(true);
    rep.getPropertyUtils().setSkipMissingProperties(true);
    Yaml yaml = new Yaml(new Constructor(MxisdConfig.class), rep);
    try (FileInputStream is = new FileInputStream(f)) {
        MxisdConfig raw = yaml.load(is);
        log.debug("Read config in memory from {}", path);

        // SnakeYaml set objects to null when there is no value set in the config, even a full sub-tree.
        // This is problematic for default config values and objects, to avoid NPEs.
        // Therefore, we'll use Gson to re-parse the data in a way that avoids us checking the whole config for nulls.
        MxisdConfig cfg = GsonUtil.get().fromJson(GsonUtil.get().toJson(raw), MxisdConfig.class);

        log.info("Loaded config from {}", path);
        return cfg;
    } catch (ParserException t) {
        throw new ConfigurationException(t.getMessage(), "Could not parse YAML config file - Please check indentation and that the configuration options exist");
    }
}
 
Example 14
Project: mollyim-android   File: FileUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static byte[] getFileDigest(FileInputStream fin) throws IOException {
  try {
    MessageDigest digest = MessageDigest.getInstance("SHA256");

    byte[] buffer = new byte[4096];
    int read = 0;

    while ((read = fin.read(buffer, 0, buffer.length)) != -1) {
      digest.update(buffer, 0, read);
    }

    return digest.digest();
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example 15
Project: dockerfile-maven   File: AbstractDockerMojo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Attempt to load a GCR compatible RegistryAuthSupplier based on a few conditions:
 * <ol>
 * <li>First check to see if the environemnt variable DOCKER_GOOGLE_CREDENTIALS is set and points
 * to a readable file</li>
 * <li>Otherwise check if the Google Application Default Credentials can be loaded</li>
 * </ol>
 * Note that we use a special environment variable of our own in addition to any environment
 * variable that the ADC loading uses (GOOGLE_APPLICATION_CREDENTIALS) in case there is a need for
 * the user to use the latter env var for some other purpose in their build.
 *
 * @return a GCR RegistryAuthSupplier, or null
 * @throws IOException if an IOException occurs while loading the credentials
 */
@Nullable
private RegistryAuthSupplier googleContainerRegistryAuthSupplier() throws IOException {
  GoogleCredentials credentials = null;

  final String googleCredentialsPath = System.getenv("DOCKER_GOOGLE_CREDENTIALS");
  if (googleCredentialsPath != null) {
    final File file = new File(googleCredentialsPath);
    if (file.exists()) {
      try (FileInputStream inputStream = new FileInputStream(file)) {
        credentials = GoogleCredentials.fromStream(inputStream);
        getLog().info("Using Google credentials from file: " + file.getAbsolutePath());
      }
    }
  }

  // use the ADC last
  if (credentials == null) {
    try {
      credentials = GoogleCredentials.getApplicationDefault();
      getLog().info("Using Google application default credentials");
    } catch (IOException ex) {
      // No GCP default credentials available
      getLog().debug("Failed to load Google application default credentials", ex);
    }
  }

  if (credentials == null) {
    return null;
  }

  return ContainerRegistryAuthSupplier.forCredentials(credentials).build();
}
 
Example 16
Project: jforgame   File: MyAgent.java    License: Apache License 2.0 5 votes vote down vote up
private static void reloadClass(File f, Instrumentation inst) throws Exception {
	byte[] targetClassFile = new byte[(int) f.length()];
	DataInputStream dis = new DataInputStream(new FileInputStream(f));
	dis.readFully(targetClassFile);
	dis.close();

	DynamicClassLoader myLoader = new DynamicClassLoader();
	Class<?> targetClazz = myLoader.findClass(targetClassFile);
	System.err.println("目标class类全路径为" + targetClazz.getName());
	ClassDefinition clazzDef = new ClassDefinition(Class.forName(targetClazz.getName()), targetClassFile);
	inst.redefineClasses(clazzDef);

	System.err.println("重新定义" + targetClazz.getName() + "完成!!");
}
 
Example 17
Project: jdk8u_nashorn   File: FXShell.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Load and evaluate the specified JavaScript file.
 *
 * @param path Path to UTF-8 encoded JavaScript file.
 *
 * @return Last evaluation result (discarded.)
 */
@SuppressWarnings("resource")
private Object load(String path) {
    try {
        FileInputStream file = new FileInputStream(path);
        InputStreamReader input = new InputStreamReader(file, "UTF-8");
        return engine.eval(input);
    } catch (FileNotFoundException | UnsupportedEncodingException | ScriptException ex) {
        ex.printStackTrace();
    }

    return null;
}
 
Example 18
Project: stratio-cassandra   File: DataOutputTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSequentialWriter() throws IOException
{
    File file = FileUtils.createTempFile("dataoutput", "test");
    final SequentialWriter writer = new SequentialWriter(file, 32);
    DataOutputStreamAndChannel write = new DataOutputStreamAndChannel(writer, writer);
    DataInput canon = testWrite(write);
    write.flush();
    write.close();
    DataInputStream test = new DataInputStream(new FileInputStream(file));
    testRead(test, canon);
    test.close();
    Assert.assertTrue(file.delete());
}
 
Example 19
Project: cellery-security   File: FileBasedKeyResolver.java    License: Apache License 2.0 5 votes vote down vote up
private void readCertificate(String publicKeyPath) throws CertificateException, IOException {

        CertificateFactory fact = CertificateFactory.getInstance("X.509");
        try (FileInputStream fileInputStream = new FileInputStream(publicKeyPath)) {
            certificate = (X509Certificate) fact.generateCertificate(fileInputStream);
            publicKey = certificate.getPublicKey();
        }
    }
 
Example 20
Project: snowblossom   File: LogSetup.java    License: Apache License 2.0 5 votes vote down vote up
public static void setup(Config config)
  throws java.io.IOException
{

  if (config.isSet("log_config_file"))
  {
    try
    {
      log_props.load(new FileInputStream(config.get("log_config_file")));
      LogManager.getLogManager().readConfiguration(new FileInputStream(config.get("log_config_file")));
    }
    catch (Exception e)
    {
      System.out.println("FAILED TO INITIALIZE LOGGING: " + e);
    }
    
  }
  else
  {
    log_props.setProperty(".level", "FINE");
    log_props.setProperty("io.level", "SEVERE");
  }

  


  //listLoggers();
}
 
Example 21
@Test
public void shouldReplaceWithPackagedCommandRepositoryWhenOlderRepoExists() throws Exception {
    File versionFile = TestFileUtil.writeStringToTempFileInFolder("default", "version.txt", "10.1=10");
    File randomFile = TestFileUtil.createTestFile(versionFile.getParentFile(), "random");
    File defaultCommandRepoDir = versionFile.getParentFile();

    initializer.usePackagedCommandRepository(new ZipInputStream(new FileInputStream(getZippedCommandRepo("12.4=12"))), defaultCommandRepoDir);

    assertThat(defaultCommandRepoDir.exists(), is(true));
    assertThat(FileUtils.readFileToString(new File(defaultCommandRepoDir, "version.txt"), UTF_8), is("12.4=12"));
    assertThat(new File(defaultCommandRepoDir, "snippet.xml").exists(), is(true));
    assertThat(new File(defaultCommandRepoDir, randomFile.getName()).exists(), is(false));
}
 
Example 22
Project: EDDI   File: RestGitBackupService.java    License: Apache License 2.0 5 votes vote down vote up
private void importBot(String botId, Integer version) throws IOException {
    String zipFilename = prepareZipFilename(botId, version);
    String targetZipPath = FileUtilities.buildPath(tmpPath, zipFilename);
    deleteFileIfExists(Paths.get(targetZipPath));
    this.zipArchive.createZip(tmpPath, targetZipPath);
    importService.importBot(new FileInputStream(targetZipPath), null);
}
 
Example 23
Project: org.hl7.fhir.core   File: ToolsHelper.java    License: Apache License 2.0 5 votes vote down vote up
public void executeCanonicalXml(String[] args) throws FHIRException, IOException {
	FileInputStream in;
	File source = new CSFile(args[1]);
	File dest = new CSFile(args[2]);

	if (!source.exists())        
		throw new FHIRException("Source File \""+source.getAbsolutePath()+"\" not found");
	in = new CSFileInputStream(source);
	XmlParser p = new XmlParser();
	Resource rf = p.parse(in);
	XmlParser cxml = new XmlParser();
	cxml.setOutputStyle(OutputStyle.NORMAL);
	cxml.compose(new FileOutputStream(dest), rf);
}
 
Example 24
Project: iBioSim   File: State.java    License: Apache License 2.0 5 votes vote down vote up
public static State deserialize(File f) throws FileNotFoundException,
        IOException, ClassNotFoundException {
    ObjectInputStream os = new ObjectInputStream(new FileInputStream(f));
    State zone = (State) os.readObject();
    os.close();
    return zone;
}
 
Example 25
Project: document-management-software   File: SearchOptions.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public static SearchOptions read(File file) throws FileNotFoundException, IOException, ClassNotFoundException {
	SearchOptions searchOptions = null;
	// Deserialize from a file
	ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
	try {
		// Deserialize the object
		searchOptions = (SearchOptions) in.readObject();
	} finally {
		in.close();
	}
	return searchOptions;
}
 
Example 26
Project: springboot-plugin-framework-parent   File: YamlConfigurationParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object parse(Resource resource, Class<?> pluginConfigClass)
        throws Exception{
    InputStream input = new FileInputStream(resource.getFile());
    YAMLParser yamlParser = yamlFactory.createParser(input);
    final JsonNode node = objectMapper.readTree(yamlParser);
    if(node == null){
        return pluginConfigClass.newInstance();
    }
    TreeTraversingParser treeTraversingParser = new TreeTraversingParser(node);
    return objectMapper.readValue(treeTraversingParser, pluginConfigClass);
}
 
Example 27
Project: development   File: ReportingServiceBeanTest.java    License: Apache License 2.0 5 votes vote down vote up
private static String getTestFileAsString(File file) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new FileInputStream(file));
        return XMLConverter.convertToString(doc, false)
                .replace("<!-- Copyright FUJITSU LIMITED 2017-->", "");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 28
Project: sailfish-core   File: DataManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create InputStream for known data
 * @param uri of data
 * @return InputStream
 */
@Override
public InputStream getDataInputStream(SailfishURI uri) {
       String resource = SailfishURIUtils.getMatchingValue(uri, location, SailfishURIRule.REQUIRE_RESOURCE);

	if (resource == null) {
		throw new RuntimeException("No data found for URI: " + uri);
	}

	try {
           return new FileInputStream(workspaceDispatcher.getFile(FolderType.ROOT, resource));
       } catch (FileNotFoundException e) {
           throw new ScriptRunException("Could not create data input stream [" + resource + "]", e);
       }
}
 
Example 29
Project: jdk8u-dev-jdk   File: FailingConstructors.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void verifyContents(File file) {
    try (FileInputStream fis = new FileInputStream(file)) {
        byte[] contents = FILE_CONTENTS.getBytes();
        int read, count = 0;
        while ((read = fis.read()) != -1) {
            if (read != contents[count++])  {
                fail("file contents have been altered");
                return;
            }
        }
    } catch (IOException ioe) {
        unexpected(ioe);
    }
}
 
Example 30
Project: astor   File: TraceClassVisitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Prints a disassembled view of the given class to the standard output. <p>
 * Usage: TraceClassVisitor [-debug] &lt;fully qualified class name or class
 * file name &gt;
 * 
 * @param args the command line arguments.
 * 
 * @throws Exception if the class cannot be found, or if an IO exception
 *         occurs.
 */
public static void main(final String[] args) throws Exception {
    int i = 0;
    int flags = ClassReader.SKIP_DEBUG;

    boolean ok = true;
    if (args.length < 1 || args.length > 2) {
        ok = false;
    }
    if (ok && "-debug".equals(args[0])) {
        i = 1;
        flags = 0;
        if (args.length != 2) {
            ok = false;
        }
    }
    if (!ok) {
        System.err.println("Prints a disassembled view of the given class.");
        System.err.println("Usage: TraceClassVisitor [-debug] "
                + "<fully qualified class name or class file name>");
        return;
    }
    ClassReader cr;
    if (args[i].endsWith(".class") || args[i].indexOf('\\') > -1
            || args[i].indexOf('/') > -1)
    {
        cr = new ClassReader(new FileInputStream(args[i]));
    } else {
        cr = new ClassReader(args[i]);
    }
    cr.accept(new TraceClassVisitor(new PrintWriter(System.out)),
            getDefaultAttributes(),
            flags);
}
 
Example 31
Project: opensim-gui   File: RunLabAction.java    License: Apache License 2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent e) {
    try {
        XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(
                       new FileInputStream(labFile)));
         Lab lab= (Lab)decoder.readObject();
         lab.execute();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }

}
 
Example 32
Project: JavaExercises   File: ZipDirectory.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
    if (fileToZip.isHidden()) {
        return;
    }
    if (fileToZip.isDirectory()) {
        if (fileName.endsWith("/")) {
            zipOut.putNextEntry(new ZipEntry(fileName));
            zipOut.closeEntry();
        } else {
            zipOut.putNextEntry(new ZipEntry(fileName + "/"));
            zipOut.closeEntry();
        }
        File[] children = fileToZip.listFiles();
        for (File childFile : children) {
            zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
        }
        return;
    }
    FileInputStream fis = new FileInputStream(fileToZip);
    ZipEntry zipEntry = new ZipEntry(fileName);
    zipOut.putNextEntry(zipEntry);
    byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zipOut.write(bytes, 0, length);
    }
    fis.close();
}
 
Example 33
Project: openjdk-8   File: CompileFontConfig.java    License: GNU General Public License v2.0 5 votes vote down vote up
CompileFontConfig(String inFile, String outFile, boolean verbose) {
    try {
        FileInputStream in = new FileInputStream(inFile);
        FileOutputStream out = new FileOutputStream(outFile);
        FontConfiguration.verbose = verbose;
        FontConfiguration.loadProperties(in);
        FontConfiguration.saveBinary(out);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 34
Project: openjdk-jdk8u   File: ClassFile.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns input stream to either regular file or zip file entry
 */
public InputStream getInputStream() throws IOException {
    if (file != null) {
        return new FileInputStream(file);
    } else {
        try {
            return zipFile.getInputStream(zipEntry);
        } catch (ZipException e) {
            throw new IOException(e.getMessage());
        }
    }
}
 
Example 35
Project: chappiecast   File: CordovaResourceApi.java    License: Mozilla Public License 2.0 5 votes vote down vote up
public void copyResource(OpenForReadResult input, OutputStream outputStream) throws IOException {
    assertBackgroundThread();
    try {
        InputStream inputStream = input.inputStream;
        if (inputStream instanceof FileInputStream && outputStream instanceof FileOutputStream) {
            FileChannel inChannel = ((FileInputStream)input.inputStream).getChannel();
            FileChannel outChannel = ((FileOutputStream)outputStream).getChannel();
            long offset = 0;
            long length = input.length;
            if (input.assetFd != null) {
                offset = input.assetFd.getStartOffset();
            }
            // transferFrom()'s 2nd arg is a relative position. Need to set the absolute
            // position first.
            inChannel.position(offset);
            outChannel.transferFrom(inChannel, 0, length);
        } else {
            final int BUFFER_SIZE = 8192;
            byte[] buffer = new byte[BUFFER_SIZE];
            
            for (;;) {
                int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);
                
                if (bytesRead <= 0) {
                    break;
                }
                outputStream.write(buffer, 0, bytesRead);
            }
        }            
    } finally {
        input.inputStream.close();
        if (outputStream != null) {
            outputStream.close();
        }
    }
}
 
Example 36
Project: org.hl7.fhir.core   File: ToolsHelper.java    License: Apache License 2.0 5 votes vote down vote up
private byte[] loadFromFile(String src) throws IOException {
	FileInputStream in = new FileInputStream(src);
	byte[] b = new byte[in.available()];
	in.read(b);
	in.close();
	return b;
}
 
Example 37
Project: HaoReader   File: DocumentHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static boolean writeFromFile(File fromFile, DocumentFile file) {
    if (file == null)
        return false;
    try {
        return DocumentUtil.writeFromInputStream(ContextHolder.getContext(), new FileInputStream(fromFile), file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 38
Project: JavaLinuxNet   File: SocketUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static int getFd(final FileInputStream stream )  {
    try {
        final FileDescriptor fd = getFileDescriptor(stream);
        return getFileHandle(fd);
    } catch (final Exception shoutNotHappen) {
        throw new JVMException(shoutNotHappen);
    }
}
 
Example 39
Project: jpexs-decompiler   File: Uploader.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Adds a upload file section to the request
 *
 * @param fieldName name attribute in <input type="file" name="..." />
 * @param uploadFile a File to be uploaded
 * @throws IOException
 */
public void addFilePart(String fieldName, File uploadFile)
        throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append(
            "Content-Disposition: form-data; name=\"" + fieldName
            + "\"; filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append(
            "Content-Type: "
            + URLConnection.guessContentTypeFromName(fileName))
            .append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();

    writer.append(LINE_FEED);
    writer.flush();
}
 
Example 40
public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
    KualiBatchFileAdminForm fileAdminForm = (KualiBatchFileAdminForm) form;
    String filePath = BatchFileUtils.resolvePathToAbsolutePath(fileAdminForm.getFilePath());
    File file = new File(filePath).getAbsoluteFile();
    
    if (!file.exists() || !file.isFile()) {
        throw new RuntimeException("Error: non-existent file or directory provided");
    }
    File containingDirectory = file.getParentFile();
    if (!BatchFileUtils.isDirectoryAccessible(containingDirectory.getAbsolutePath())) {
        throw new RuntimeException("Error: inaccessible directory provided");
    }
    
    BatchFile batchFile = new BatchFile();
    batchFile.setFile(file);
    if (!SpringContext.getBean(BatchFileAdminAuthorizationService.class).canDownload(batchFile, GlobalVariables.getUserSession().getPerson())) {
        throw new RuntimeException("Error: not authorized to download file");
    }
    
    response.setContentType("application/octet-stream");
    response.setHeader("Content-disposition", "attachment; filename=" + file.getName());
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength((int) file.length());

    InputStream fis = new FileInputStream(file);
    IOUtils.copy(fis, response.getOutputStream());
    response.getOutputStream().flush();
    return null;
}