Java Code Examples for java.io.BufferedInputStream

The following examples show how to use java.io.BufferedInputStream. These examples are extracted from open source projects.
Example 1
Project: TencentKona-8   File: FuncSystemProperty.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Retrieve a propery bundle from a specified file
 *
 * @param file The string name of the property file.  The name
 * should already be fully qualified as path/filename
 * @param target The target property bag the file will be placed into.
 */
public void loadPropertyFile(String file, Properties target)
{
  try
  {
    // Use SecuritySupport class to provide priveleged access to property file
    InputStream is = SecuritySupport.getResourceAsStream(ObjectFactory.findClassLoader(),
                                            file);

    // get a buffered version
    BufferedInputStream bis = new BufferedInputStream(is);

    target.load(bis);  // and load up the property bag from this
    bis.close();  // close out after reading
  }
  catch (Exception ex)
  {
    // ex.printStackTrace();
    throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(ex);
  }
}
 
Example 2
Project: FastAsyncWorldedit   File: MCAFile.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void streamChunk(byte[] data, RunnableVal<NBTStreamer> withStream) throws IOException {
    if (data != null) {
        try {
            FastByteArrayInputStream nbtIn = new FastByteArrayInputStream(data);
            FastByteArrayInputStream bais = new FastByteArrayInputStream(data);
            InflaterInputStream iis = new InflaterInputStream(bais, new Inflater(), 1);
            fieldBuf2.set(iis, byteStore2.get());
            BufferedInputStream bis = new BufferedInputStream(iis);
            NBTInputStream nis = new NBTInputStream(bis);
            fieldBuf3.set(nis, byteStore3.get());
            NBTStreamer streamer = new NBTStreamer(nis);
            withStream.run(streamer);
            streamer.readQuick();
        } catch (IllegalAccessException unlikely) {
            unlikely.printStackTrace();
        }
    }
}
 
Example 3
Project: Wikidata-Toolkit   File: DirectoryManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns an input stream that applies the required decompression to the
 * given input stream.
 *
 * @param inputStream
 *            the input stream with the (possibly compressed) data
 * @param compressionType
 *            the kind of compression
 * @return an input stream with decompressed data
 * @throws IOException
 *             if there was a problem creating the decompression streams
 */
protected InputStream getCompressorInputStream(InputStream inputStream,
		CompressionType compressionType) throws IOException {
	switch (compressionType) {
	case NONE:
		return inputStream;
	case GZIP:
		return new GZIPInputStream(inputStream);
	case BZ2:
		return new BZip2CompressorInputStream(new BufferedInputStream(
				inputStream));
	default:
		throw new IllegalArgumentException("Unsupported compression type: "
				+ compressionType);
	}
}
 
Example 4
Project: openjdk-8-source   File: StandardMidiFileReader.java    License: GNU General Public License v2.0 6 votes vote down vote up
public MidiFileFormat getMidiFileFormat(File file) throws InvalidMidiDataException, IOException {
    FileInputStream fis = new FileInputStream(file); // throws IOException
    BufferedInputStream bis = new BufferedInputStream(fis, bisBufferSize);

    // $$fb 2002-04-17: part of fix for 4635286: MidiSystem.getMidiFileFormat() returns format having invalid length
    long length = file.length();
    if (length > Integer.MAX_VALUE) {
        length = MidiFileFormat.UNKNOWN_LENGTH;
    }
    MidiFileFormat fileFormat = null;
    try {
        fileFormat = getMidiFileFormatFromStream(bis, (int) length, null);
    } finally {
        bis.close();
    }
    return fileFormat;
}
 
Example 5
Project: wind-im   File: FileUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void writeResourceToFile(String resourceName, File file) throws FileNotFoundException, IOException {
	if (!file.exists()) {
		new FileOutputStream(file).close();
	}
	InputStream is = MysqlManager.class.getResourceAsStream(resourceName);
	BufferedInputStream bis = new BufferedInputStream(is);
	FileOutputStream fos = new FileOutputStream(file);
	try {
		byte[] buffer = new byte[1024];
		int bytesLen = 0;
		while ((bytesLen = bis.read(buffer)) != -1) {
			fos.write(buffer, 0, bytesLen);
		}
	} finally {
		if (bis != null) {
			bis.close();
		}
		if (is != null) {
			is.close();
		}
		if (fos != null) {
			fos.close();
		}
	}
}
 
Example 6
Project: sensorhub   File: DefaultModuleStateManager.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Override
public InputStream getAsInputStream(String key)
{
    File dataFile = getDataFile(key);
    
    try
    {
        if (dataFile.exists())
            return new BufferedInputStream(new FileInputStream(dataFile));
    }
    catch (FileNotFoundException e)
    {
    }
    
    return null;
}
 
Example 7
Project: JReFrameworker   File: JarModifier.java    License: MIT License 6 votes vote down vote up
public byte[] extractEntry(String entry) throws IOException {
	JarInputStream zin = new JarInputStream(new BufferedInputStream(new FileInputStream(jarFile)));
	JarEntry currentEntry = null;
	while ((currentEntry = zin.getNextJarEntry()) != null) {
		if (currentEntry.getName().equals(entry)) {
			// currentEntry.getSize() may not be accurate, so read bytes into a stream first
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buf = new byte[4096];
			while (true) {
				int n = zin.read(buf);
				if (n < 0){
					break;
				}
				baos.write(buf, 0, n);
			}
			zin.close();
			return baos.toByteArray();
		}
	}
	zin.close();
	return null;
}
 
Example 8
/**
 * @return null if we were unable to load the cached version
 */
public GrammaticalLabelSetImpl read() {
    // if we're tracking duplicated labels, we need to load the file directly in order to look at all the labels, so don't load from the cache
    if (this.language == LanguageProviderFactory.get().getBaseLanguage() && GrammaticalLabelFileParser.isDupeLabelTrackingEnabled()) {
        return null;
    }

    logger.info("Loading " + labelSetName + " from cache");
    long start = System.currentTimeMillis();
    try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(this.cacheFile)))) {
        GrammaticalLabelSetImpl labelSet = (GrammaticalLabelSetImpl)ois.readObject();
        logger.info("Loaded " + this.labelSetName + " from cache in " + (System.currentTimeMillis() - start)
            + " ms");
        return labelSet;
    }
    catch (Exception e) {
        logger.log(Level.INFO, "Could not load " + labelSetName + " from cache: ", e);
        delete();
    }
    return null;
}
 
Example 9
Project: Bytecoder   File: StandardMidiFileReader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public MidiFileFormat getMidiFileFormat(File file) throws InvalidMidiDataException, IOException {
    FileInputStream fis = new FileInputStream(file); // throws IOException
    BufferedInputStream bis = new BufferedInputStream(fis, bisBufferSize);

    // $$fb 2002-04-17: part of fix for 4635286: MidiSystem.getMidiFileFormat() returns format having invalid length
    long length = file.length();
    if (length > Integer.MAX_VALUE) {
        length = MidiFileFormat.UNKNOWN_LENGTH;
    }
    MidiFileFormat fileFormat = null;
    try {
        fileFormat = getMidiFileFormatFromStream(bis, (int) length, null);
    } finally {
        bis.close();
    }
    return fileFormat;
}
 
Example 10
Project: JDKSourceCode1.8   File: FuncSystemProperty.java    License: MIT License 6 votes vote down vote up
/**
 * Retrieve a propery bundle from a specified file
 *
 * @param file The string name of the property file.  The name
 * should already be fully qualified as path/filename
 * @param target The target property bag the file will be placed into.
 */
public void loadPropertyFile(String file, Properties target)
{
  try
  {
    // Use SecuritySupport class to provide priveleged access to property file
    InputStream is = SecuritySupport.getResourceAsStream(ObjectFactory.findClassLoader(),
                                            file);

    // get a buffered version
    BufferedInputStream bis = new BufferedInputStream(is);

    target.load(bis);  // and load up the property bag from this
    bis.close();  // close out after reading
  }
  catch (Exception ex)
  {
    // ex.printStackTrace();
    throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(ex);
  }
}
 
Example 11
Project: fdroidclient   File: RepoDetails.java    License: GNU General Public License v3.0 6 votes vote down vote up
@NonNull
public static RepoDetails getFromFile(InputStream inputStream, int pushRequests) {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        RepoDetails repoDetails = new RepoDetails();
        MockRepo mockRepo = new MockRepo(100, pushRequests);
        RepoXMLHandler handler = new RepoXMLHandler(mockRepo, repoDetails);
        reader.setContentHandler(handler);
        InputSource is = new InputSource(new BufferedInputStream(inputStream));
        reader.parse(is);
        return repoDetails;
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
        fail();

        // Satisfies the compiler, but fail() will always throw a runtime exception so we never
        // reach this return statement.
        return null;
    }
}
 
Example 12
Project: netbeans   File: DocDownloader.java    License: Apache License 2.0 6 votes vote down vote up
@NonNull
public static Future<String> download(
        @NonNull final URL url,
        @NonNull final Callable<Boolean> cancel) {
    return RP.submit(()-> {
        if (cancel.call()) {
            return "";  //NOI18N
        }
        final ProgressHandle handle = ProgressHandle.createHandle(NbBundle.getMessage(DocDownloader.class, "LBL_DownloadingDoc"));
        handle.start();
        try {
            final ByteArrayOutputStream out = new ByteArrayOutputStream();
            try(BufferedInputStream in = new BufferedInputStream(url.openStream())) {
                FileUtil.copy(in, out);
            }
            return cancel.call() ?
                    ""  //NOI18N
                    : new String(out.toByteArray(),"UTF-8");  //NOI18N
        } finally {
            handle.finish();
        }
    });
}
 
Example 13
Project: jdk8u-dev-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 14
Project: ade   File: MainScorerImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public final IMainScorer load(File modelFile) throws IOException, AdeException {
    final ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(modelFile)));
    try {
        final MainScorerImpl res = (MainScorerImpl) in.readObject();
        final FlowTemplateFactory flow = Ade.getAde().getFlowFactory().getFlowByName(res.m_flowName);
        final Map<String, FramingFlowType> myFramingFlows = flow.getMyFramingFlows();
        res.m_framingFlow = myFramingFlows.get(flow.getUploadFramer());
        res.m_scorerSchemas = flow.getScorerSchemas();
        res.wakeUp();
        return res;
    } catch (ClassNotFoundException e) {
        throw new AdeUsageException("Failed loading model from file: " + modelFile.getAbsolutePath(), e);
    } finally {
        in.close();
    }
}
 
Example 15
Project: localization_nifi   File: ZooKeeperStateServer.java    License: Apache License 2.0 6 votes vote down vote up
public static ZooKeeperStateServer create(final NiFiProperties properties) throws IOException, ConfigException {
    final File propsFile = properties.getEmbeddedZooKeeperPropertiesFile();
    if (propsFile == null) {
        return null;
    }

    if (!propsFile.exists() || !propsFile.canRead()) {
        throw new IOException("Cannot create Embedded ZooKeeper Server because the Properties File " + propsFile.getAbsolutePath()
            + " referenced in nifi.properties does not exist or cannot be read");
    }

    final Properties zkProperties = new Properties();
    try (final InputStream fis = new FileInputStream(propsFile);
        final InputStream bis = new BufferedInputStream(fis)) {
        zkProperties.load(bis);
    }

    return new ZooKeeperStateServer(zkProperties);
}
 
Example 16
Project: database   File: LinkedBlockingQueueTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * A deserialized serialized queue has same elements in same order
 */
public void testSerialization() throws Exception {
    LinkedBlockingQueue q = populatedQueue(SIZE);

    ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
    out.writeObject(q);
    out.close();

    ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
    LinkedBlockingQueue r = (LinkedBlockingQueue)in.readObject();
    assertEquals(q.size(), r.size());
    while (!q.isEmpty())
        assertEquals(q.remove(), r.remove());
}
 
Example 17
Project: consulo   File: ArtifactCompilerUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
public static Pair<InputStream, Long> getArchiveEntryInputStream(VirtualFile sourceFile, final CompileContext context) throws IOException {
  final String fullPath = sourceFile.getPath();
  final int jarEnd = fullPath.indexOf(ArchiveFileSystem.ARCHIVE_SEPARATOR);
  LOG.assertTrue(jarEnd != -1, fullPath);
  String pathInJar = fullPath.substring(jarEnd + ArchiveFileSystem.ARCHIVE_SEPARATOR.length());
  String jarPath = fullPath.substring(0, jarEnd);
  final ZipFile jarFile = new ZipFile(new File(FileUtil.toSystemDependentName(jarPath)));
  final ZipEntry entry = jarFile.getEntry(pathInJar);
  if (entry == null) {
    context.addMessage(CompilerMessageCategory.ERROR, "Cannot extract '" + pathInJar + "' from '" + jarFile.getName() + "': entry not found", null, -1, -1);
    return Pair.empty();
  }

  BufferedInputStream bufferedInputStream = new BufferedInputStream(jarFile.getInputStream(entry)) {
    @Override
    public void close() throws IOException {
      super.close();
      jarFile.close();
    }
  };
  return Pair.<InputStream, Long>create(bufferedInputStream, entry.getSize());
}
 
Example 18
Project: xian   File: DefaultExhibitorRestClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception
{
    URI                 uri = new URI(useSsl ? "https" : "http", null, hostname, port, uriPath, null, null);
    HttpURLConnection   connection = (HttpURLConnection)uri.toURL().openConnection();
    connection.addRequestProperty("Accept", mimeType);
    StringBuilder       str = new StringBuilder();
    InputStream         in = new BufferedInputStream(connection.getInputStream());
    try
    {
        for(;;)
        {
            int     b = in.read();
            if ( b < 0 )
            {
                break;
            }
            str.append((char)(b & 0xff));
        }
    }
    finally
    {
        CloseableUtils.closeQuietly(in);
    }
    return str.toString();
}
 
Example 19
Project: spliceengine   File: TemporaryClob.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Finds the corresponding byte position for the given UTF-8 character
 * position, starting from the byte position <code>startPos</code>.
 * See comments in SQLChar.readExternal for more notes on
 * processing the UTF8 format.
 *
 * @param charPos character position
 * @return Stream position in bytes for the given character position.
 * @throws EOFException if the character position specified is greater than
 *      the Clob length +1
 * @throws IOException if accessing underlying I/O resources fail
 */
//@GuardedBy(this)
private long getBytePosition (final long charPos)
        throws IOException {
    long bytePos;
    if (charPos == this.posCache.getCharPos()) {
        // We already know the position.
        bytePos = this.posCache.getBytePos();
    } else {
        long startingBytePosition = 0L; // Default to start at position 0.
        long charsToSkip = charPos -1; // Subtract one to get number to skip
        if (charPos > this.posCache.getCharPos()) {
            // Exploit the last known character position.
            startingBytePosition = this.posCache.getBytePos();
            charsToSkip -= (this.posCache.getCharPos() -1);
        }
        InputStream utf8Bytes =
            this.bytes.getInputStream(startingBytePosition);
        bytePos = startingBytePosition +
            UTF8Util.skipFully(new BufferedInputStream(utf8Bytes),
                               charsToSkip);
        this.posCache.updateCachedPos(charPos, bytePos);
    }
    return bytePos;
}
 
Example 20
Project: sofa-jraft   File: ProtoBufFile.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Load a protobuf message from file.
 */
public <T extends Message> T load() throws IOException {
    File file = new File(this.path);

    if (!file.exists()) {
        return null;
    }

    final byte[] lenBytes = new byte[4];
    try (final FileInputStream fin = new FileInputStream(file);
            final BufferedInputStream input = new BufferedInputStream(fin)) {
        readBytes(lenBytes, input);
        final int len = Bits.getInt(lenBytes, 0);
        if (len <= 0) {
            throw new IOException("Invalid message fullName.");
        }
        final byte[] nameBytes = new byte[len];
        readBytes(nameBytes, input);
        final String name = new String(nameBytes);
        readBytes(lenBytes, input);
        final int msgLen = Bits.getInt(lenBytes, 0);
        final byte[] msgBytes = new byte[msgLen];
        readBytes(msgBytes, input);
        return ProtobufMsgFactory.newMessageByProtoClassName(name, msgBytes);
    }
}
 
Example 21
Project: Telegram   File: AudioInfo.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static AudioInfo getAudioInfo(File file) {
     try {
         byte header[] = new byte[12];
         RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
         randomAccessFile.readFully(header, 0, 8);
         randomAccessFile.close();
         InputStream input = new BufferedInputStream(new FileInputStream(file));
         if (header[4] == 'f' && header[5] == 't' && header[6] == 'y' && header[7] == 'p') {
             return new M4AInfo(input);
         } else if (file.getAbsolutePath().endsWith("mp3")) {
             return new MP3Info(input, file.length());
         } else {
         	return null;
}
     } catch (Exception e) {
         return null;
     }
 }
 
Example 22
Project: openjdk-jdk8u-backup   File: WaveFloatFileReader.java    License: GNU General Public License v2.0 5 votes vote down vote up
public AudioFileFormat getAudioFileFormat(URL url)
        throws UnsupportedAudioFileException, IOException {
    InputStream stream = url.openStream();
    AudioFileFormat format;
    try {
        format = getAudioFileFormat(new BufferedInputStream(stream));
    } finally {
        stream.close();
    }
    return format;
}
 
Example 23
Project: TencentKona-8   File: HttpAwareServerSocket.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Accept a connection. This method will block until the connection
 * is made and four bytes can be read from the input stream.
 * If the first four bytes are "POST", then an HttpReceiveSocket is
 * returned, which will handle the HTTP protocol wrapping.
 * Otherwise, a WrappedSocket is returned.  The input stream will be
 * reset to the beginning of the transmission.
 * In either case, a BufferedInputStream will already be on top of
 * the underlying socket's input stream.
 * @exception IOException IO error when waiting for the connection.
 */
public Socket accept() throws IOException
{
    Socket socket = super.accept();
    BufferedInputStream in =
        new BufferedInputStream(socket.getInputStream());

    RMIMasterSocketFactory.proxyLog.log(Log.BRIEF,
        "socket accepted (checking for POST)");

    in.mark(4);
    boolean isHttp = (in.read() == 'P') &&
                     (in.read() == 'O') &&
                     (in.read() == 'S') &&
                     (in.read() == 'T');
    in.reset();

    if (RMIMasterSocketFactory.proxyLog.isLoggable(Log.BRIEF)) {
        RMIMasterSocketFactory.proxyLog.log(Log.BRIEF,
            (isHttp ? "POST found, HTTP socket returned" :
                      "POST not found, direct socket returned"));
    }

    if (isHttp)
        return new HttpReceiveSocket(socket, in, null);
    else
        return new WrappedSocket(socket, in, null);
}
 
Example 24
Project: synapse   File: KinesisCompactionAcceptanceTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private LinkedHashMap<String, JSONArray> fetchAndParseSnapshotFileFromS3(String snapshotFileName) {
    GetObjectRequest request = GetObjectRequest.builder().bucket(INTEGRATION_TEST_BUCKET).key(snapshotFileName).build();

    ResponseInputStream<GetObjectResponse> responseInputStream = s3Client.getObject(request);
    try (
            BufferedInputStream bufferedInputStream = new BufferedInputStream(responseInputStream);
            ZipInputStream zipInputStream = new ZipInputStream(bufferedInputStream)
    ) {
        zipInputStream.getNextEntry();
        return (LinkedHashMap<String, JSONArray>) Configuration.defaultConfiguration().jsonProvider().parse(zipInputStream, Charsets.UTF_8.name());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 25
Project: slick2d-maven   File: CompositeImageData.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @see org.newdawn.slick.opengl.LoadableImageData#loadImage(java.io.InputStream, boolean, boolean, int[])
 */
public ByteBuffer loadImage(InputStream is, boolean flipped, boolean forceAlpha, int[] transparent) throws IOException {
	CompositeIOException exception = new CompositeIOException();
	ByteBuffer buffer = null;
	
	BufferedInputStream in = new BufferedInputStream(is, is.available());
	in.mark(is.available());
	
	// cycle through our source until one of them works
	for (int i=0;i<sources.size();i++) {
		in.reset();
		try {
			LoadableImageData data = (LoadableImageData) sources.get(i);
			
			buffer = data.loadImage(in, flipped, forceAlpha, transparent);
			picked = data;
			break;
		} catch (Exception e) {
			Log.warn(sources.get(i).getClass()+" failed to read the data", e);
			exception.addException(e);
		}
	}
	
	if (picked == null) {
		throw exception;
	}
	
	return buffer;
}
 
Example 26
Project: logging-log4j2   File: LoggerBufferedInputStreamCallerInfoTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setupStreams() {
    final InputStream srcInputStream = new ByteArrayInputStream("a\nb\nc\nd".getBytes());
    this.logIn = (BufferedInputStream)
        IoBuilder.forLogger(getLogger())
            .filter(srcInputStream)
            .setLevel(LEVEL)
            .setBuffered(true)
            .buildInputStream();
}
 
Example 27
Project: netbeans   File: WLJpa2SwitchSupport.java    License: Apache License 2.0 5 votes vote down vote up
private void copy(File source, File dest) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(source));
    try {
        OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));
        try {
            FileUtil.copy(is, os);
        } finally {
            os.close();
        }
    } finally {
        is.close();
    }
}
 
Example 28
Project: jdk8u_jdk   File: WaveExtensibleFileReader.java    License: GNU General Public License v2.0 5 votes vote down vote up
public AudioFileFormat getAudioFileFormat(URL url)
        throws UnsupportedAudioFileException, IOException {
    InputStream stream = url.openStream();
    AudioFileFormat format;
    try {
        format = getAudioFileFormat(new BufferedInputStream(stream));
    } finally {
        stream.close();
    }
    return format;
}
 
Example 29
Project: j2objc   File: OldLineNumberInputStreamTest.java    License: Apache License 2.0 5 votes vote down vote up
protected void setUp() {
    /*
     * In order for IOException to be thrown in reset(),the inputStream to
     * the constructor cannot be a byteArrayInputstream because the reset()
     * in byteArrayInputStream does not throw IOException. When
     * BufferedInputStream is used, the size of the buffer must be smaller
     * than the readlimit in mark inorder for IOException to be thrown
     */
    BufferedInputStream buftemp = new BufferedInputStream(
            new ByteArrayInputStream(text.getBytes()), 4);
    lnis = new LineNumberInputStream(buftemp);
    lnis2 = new LineNumberInputStream(new ByteArrayInputStream(dosText
            .getBytes()));
}
 
Example 30
Project: olat   File: TextDocument.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected String readContent(final VFSLeaf leaf) throws IOException {
    final BufferedInputStream bis = new BufferedInputStream(leaf.getInputStream());
    final String content = FileUtils.load(bis, "utf-8");
    bis.close();
    return content;
}
 
Example 31
Project: openjdk-8   File: JavaSoundAudioClip.java    License: GNU General Public License v2.0 5 votes vote down vote up
private boolean createSequencer(BufferedInputStream in) throws IOException {

        if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createSequencer()");

        // get the sequencer
        try {
            sequencer = MidiSystem.getSequencer( );
        } catch(MidiUnavailableException me) {
            if (DEBUG || Printer.err)me.printStackTrace();
            return false;
        }
        if (sequencer==null) {
            return false;
        }

        try {
            sequence = MidiSystem.getSequence(in);
            if (sequence == null) {
                return false;
            }
        } catch (InvalidMidiDataException e) {
            if (DEBUG || Printer.err)e.printStackTrace();
            return false;
        }

        if (DEBUG || Printer.debug)Printer.debug("Created Sequencer.");
        return true;
    }
 
Example 32
Project: cordova-hot-code-push   File: FilesUtility.java    License: MIT License 5 votes vote down vote up
private static void copyFile(File fromFile, File toFile) throws IOException {
    InputStream in = new BufferedInputStream(new FileInputStream(fromFile));
    OutputStream out = new BufferedOutputStream(new FileOutputStream(toFile));

    // Transfer bytes from in to out
    byte[] buf = new byte[8192];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }

    in.close();
    out.close();
}
 
Example 33
Project: nifi   File: FileSystemSwapManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SwapContents peek(final String swapLocation, final FlowFileQueue flowFileQueue) throws IOException {
    final File swapFile = new File(swapLocation);
    if (!swapFile.exists()) {
        throw new FileNotFoundException("Failed to swap in FlowFiles from external storage location " + swapLocation + " into FlowFile Queue because the file could not be found");
    }

    try (final InputStream fis = new FileInputStream(swapFile);
            final InputStream bis = new BufferedInputStream(fis);
            final DataInputStream in = new DataInputStream(bis)) {

        final SwapDeserializer deserializer = createSwapDeserializer(in);
        return deserializer.deserializeFlowFiles(in, swapLocation, flowFileQueue, claimManager);
    }
}
 
Example 34
Project: hottub   File: OptimisticTypesPersistence.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Loads the map of optimistic types for a given function.
 * @param locationDescriptor the opaque persistence location descriptor, retrieved by calling
 * {@link #getLocationDescriptor(Source, int, Type[])}.
 * @return the map of optimistic types, or null if persisted type information could not be retrieved.
 */
@SuppressWarnings("resource")
public static Map<Integer, Type> load(final Object locationDescriptor) {
    if (locationDescriptor == null) {
        return null;
    }
    final File file = ((LocationDescriptor)locationDescriptor).file;
    return AccessController.doPrivileged(new PrivilegedAction<Map<Integer, Type>>() {
        @Override
        public Map<Integer, Type> run() {
            try {
                if(!file.isFile()) {
                    return null;
                }
                synchronized(getFileLock(file)) {
                    try (final FileInputStream in = new FileInputStream(file)) {
                        in.getChannel().lock(0, Long.MAX_VALUE, true); // lock shared
                        final DataInputStream din = new DataInputStream(new BufferedInputStream(in));
                        return Type.readTypeMap(din);
                    }
                }
            } catch (final Exception e) {
                reportError("read", file, e);
                return null;
            }
        }
    });
}
 
Example 35
Project: components   File: AvroHdfsFileSink.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void mergeOutput(FileSystem fs, String sourceFolder, String targetFile) throws IOException {
    try (DataFileWriter<GenericRecord> writer = new DataFileWriter<GenericRecord>(new GenericDatumWriter<GenericRecord>())) {
        FileStatus[] sourceStatuses = FileSystemUtil.listSubFiles(fs, sourceFolder);
        Schema schema = null;
        String inputCodec = null;
        OutputStream output = new BufferedOutputStream(fs.create(new Path(targetFile)));
        for (FileStatus sourceStatus : sourceStatuses) {
            try (DataFileStream<GenericRecord> reader = new DataFileStream<GenericRecord>(
                    new BufferedInputStream(fs.open(sourceStatus.getPath())), new GenericDatumReader<GenericRecord>())) {

                if (schema == null) {
                    schema = reader.getSchema();
                    for (String key : reader.getMetaKeys()) {
                        if (!DataFileWriter.isReservedMeta(key)) {
                            writer.setMeta(key, reader.getMeta(key));
                        }
                    }
                    inputCodec = reader.getMetaString(DataFileConstants.CODEC);
                    if (inputCodec == null) {
                        inputCodec = DataFileConstants.NULL_CODEC;
                    }
                    writer.setCodec(CodecFactory.fromString(inputCodec));
                    writer.create(schema, output);
                }
                writer.appendAllFrom(reader, false);
            }
        }
    }
}
 
Example 36
Project: Java-Unserialization-Study   File: ExportObject.java    License: MIT License 5 votes vote down vote up
public static String exec(String cmd) throws Exception {
    String sb = "";
    BufferedInputStream in = new BufferedInputStream(Runtime.getRuntime().exec(cmd).getInputStream());
    BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
    String lineStr;
    while ((lineStr = inBr.readLine()) != null)
        sb += lineStr + "\n";
    inBr.close();
    in.close();
    return sb;
}
 
Example 37
Project: jclic   File: Converter.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected InputStream openInput(String fileName)
	throws IOException
{
	// ensure name is abstract path name
	File file = new File(fileName);
	InputStream fileIn = new FileInputStream(file);
	BufferedInputStream bufIn = new BufferedInputStream(fileIn);

	return bufIn;
}
 
Example 38
Project: netbeans   File: EclipseUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Load properties from a given <code>file</code>.
 * <p>
 * <strong>Note: package private for unit tests only.</strong>
 * 
 * @throws IOException when reading file failed
 */
static Map<String,String> loadProperties(File file) throws IOException {
    InputStream propsIS = new BufferedInputStream(new FileInputStream(file));
    Properties properties = new Properties();
    try {
        properties.load(propsIS);
    } finally {
        propsIS.close();
    }
    return NbCollections.checkedMapByFilter(properties, String.class, String.class, true);
}
 
Example 39
Project: opsu   File: ImageLoader.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
	// load image data into a ByteBuffer to use constructor Image(ImageData)
	LoadableImageData imageData = ImageDataFactory.getImageDataFor(file.getAbsolutePath());
	try (BufferedInputStream in = this.in = new BufferedInputStream(new FileInputStream(file))) {
		ByteBuffer textureBuffer = imageData.loadImage(in, false, null);
		if (!isInterrupted())
			data = new LoadedImageData(imageData, textureBuffer);
	} catch (Exception e) {
		if (!isInterrupted())
			Log.warn(String.format("Failed to load background image '%s'.", file), e);
	}
	this.in = null;
}
 
Example 40
Project: TencentKona-8   File: WaveFloatFileReader.java    License: GNU General Public License v2.0 5 votes vote down vote up
public AudioFileFormat getAudioFileFormat(URL url)
        throws UnsupportedAudioFileException, IOException {
    InputStream stream = url.openStream();
    AudioFileFormat format;
    try {
        format = getAudioFileFormat(new BufferedInputStream(stream));
    } finally {
        stream.close();
    }
    return format;
}