Java Code Examples for java.io.InputStream.close()

The following are Jave code examples for showing how to use close() of the java.io.InputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: XMLBaseParser   File: MainActivity.java   View Source Code Vote up 6 votes
private void doLocalXMLParser(){
    try {
        //Return an AssetManager instance for your application's package
        InputStream is = getAssets().open("test.xml");
        int size = is.available();
        // Read the entire asset into a local byte buffer.
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

        // Convert the buffer into a string.
        String xmlData = new String(buffer, "UTF-8");
        beginParser(xmlData);
    } catch (IOException e) {
        // Should never happen!
        throw new RuntimeException(e);
    }
}
 
Example 2
Project: AndroidBasicLibs   File: CpuUtil.java   View Source Code Vote up 6 votes
/**
 * Get command output string.
 */
public static String getCMDOutputString(String[] args) {
    try {
        ProcessBuilder cmd = new ProcessBuilder(args);
        Process process = cmd.start();
        InputStream in = process.getInputStream();
        StringBuilder sb = new StringBuilder();
        byte[] re = new byte[64];
        int len;
        while ((len = in.read(re)) != -1) {
            sb.append(new String(re, 0, len));
        }
        in.close();
        process.destroy();
        JLog.i("CMD: " + sb.toString());
        return sb.toString();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return null;
}
 
Example 3
Project: neoscada   File: LocalDataPage.java   View Source Code Vote up 6 votes
protected void loadData ( final File file ) throws Exception
{
    if ( OscarLoader.isOscar ( file ) )
    {
        final OscarLoader loader = new OscarLoader ( file );
        this.mergeController.setLocalData ( loader.getData () );
        this.mergeController.setIgnoreFields ( loader.getIgnoreFields () );
    }
    else
    {
        final InputStream stream = new FileInputStream ( file );
        try
        {
            this.mergeController.setLocalData ( OscarLoader.loadJsonData ( stream ) );
        }
        finally
        {
            stream.close ();
        }
    }
}
 
Example 4
Project: GIFKR   File: CalebKussmaul.java   View Source Code Vote up 6 votes
public static boolean refresh(){
	props 							= new Properties();
	try {
		URLConnection connection	= new URL("http://kussmaul.net/projects.properties").openConnection();
		connection.setConnectTimeout(1000);
		final InputStream in = connection.getInputStream();
		props.load(in);
		if(!props.containsKey("ServerIP"))
			throw new Exception("Something wrong with download");
		in.close();
		return true;
	} catch (Exception e) {
		e.printStackTrace();
		props						= getDefaultProperties();
		return false;
	}
}
 
Example 5
Project: Microsphere   File: Utils.java   View Source Code Vote up 6 votes
public static String exportResource(Context context, int resourceId, String dirname) {
    String fullname = context.getResources().getString(resourceId);
    String resName = fullname.substring(fullname.lastIndexOf("/") + 1);
    try {
        InputStream is = context.getResources().openRawResource(resourceId);
        File resDir = context.getDir(dirname, Context.MODE_PRIVATE);
        File resFile = new File(resDir, resName);

        FileOutputStream os = new FileOutputStream(resFile);

        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        is.close();
        os.close();

        return resFile.getAbsolutePath();
    } catch (IOException e) {
        e.printStackTrace();
        throw new CvException("Failed to export resource " + resName
                + ". Exception thrown: " + e);
    }
}
 
Example 6
Project: hadoop   File: TestHFSTestCase.java   View Source Code Vote up 6 votes
@Test
@TestHdfs
public void testHadoopFileSystem() throws Exception {
  Configuration conf = TestHdfsHelper.getHdfsConf();
  FileSystem fs = FileSystem.get(conf);
  try {
    OutputStream os = fs.create(new Path(TestHdfsHelper.getHdfsTestDir(), "foo"));
    os.write(new byte[]{1});
    os.close();
    InputStream is = fs.open(new Path(TestHdfsHelper.getHdfsTestDir(), "foo"));
    assertEquals(is.read(), 1);
    assertEquals(is.read(), -1);
    is.close();
  } finally {
    fs.close();
  }
}
 
Example 7
Project: lams   File: AbstractReloadingMetadataProvider.java   View Source Code Vote up 6 votes
/**
 * Converts an InputStream into a byte array.
 * 
 * @param ins input stream to convert
 * 
 * @return resultant byte array
 * 
 * @throws MetadataProviderException thrown if there is a problem reading the resultant byte array
 */
protected byte[] inputstreamToByteArray(InputStream ins) throws MetadataProviderException {
    try {
        // 1 MB read buffer
        byte[] buffer = new byte[1024 * 1024];
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        int n = 0;
        while (-1 != (n = ins.read(buffer))) {
            output.write(buffer, 0, n);
        }

        ins.close();
        return output.toByteArray();
    } catch (IOException e) {
        throw new MetadataProviderException(e);
    }
}
 
Example 8
Project: Moenagade   File: DemuxInputStream.java   View Source Code Vote up 5 votes
/**
 * Closes stream associated with current thread.
 *
 * @throws IOException if an error occurs
 */
@Override
public void close()
    throws IOException
{
    InputStream input = m_streams.get();
    if( null != input )
    {
        input.close();
    }
}
 
Example 9
Project: WeatherAlarmClock   File: AlarmClockService.java   View Source Code Vote up 5 votes
private static void copyFile(File file, InputStream is, String mode)
        throws IOException, InterruptedException {
    final String abspath = file.getAbsolutePath();
    final FileOutputStream out = new FileOutputStream(file);
    byte buf[] = new byte[1024];
    int len;
    while ((len = is.read(buf)) > 0) {
        out.write(buf, 0, len);
    }

    out.close();
    is.close();

    Runtime.getRuntime().exec("chmod " + mode + " " + abspath).waitFor();
}
 
Example 10
Project: ibm-cos-sdk-java   File: ResettableInputStreamTest.java   View Source Code Vote up 5 votes
@Test
public void testFileInputStream() throws IOException {
    InputStream is = new FileInputStream(file);
    assertFalse(is.markSupported());
    final String content = IOUtils.toString(is);
    final String content2 = IOUtils.toString(is);
    assertTrue(content.length() == 100);
    assertEquals(content2, "");
    is.close();
}
 
Example 11
Project: GitHub   File: UpdateDownloader.java   View Source Code Vote up 5 votes
private int copy(InputStream in, RandomAccessFile out) throws IOException, UpdateError {

        byte[] buffer = new byte[BUFFER_SIZE];
        BufferedInputStream bis = new BufferedInputStream(in, BUFFER_SIZE);
        try {

            out.seek(out.length());

            int bytes = 0;
            long previousBlockTime = -1;

            while (!isCancelled()) {
                int n = bis.read(buffer, 0, BUFFER_SIZE);
                if (n == -1) {
                    break;
                }
                out.write(buffer, 0, n);
                bytes += n;

                checkNetwork();

                if (mSpeed != 0) {
                    previousBlockTime = -1;
                } else if (previousBlockTime == -1) {
                    previousBlockTime = System.currentTimeMillis();
                } else if ((System.currentTimeMillis() - previousBlockTime) > TIME_OUT) {
                    throw new UpdateError(UpdateError.DOWNLOAD_NETWORK_TIMEOUT);
                }
            }
            return bytes;
        } finally {
            out.close();
            bis.close();
            in.close();
        }
    }
 
Example 12
Project: mczone   File: Files.java   View Source Code Vote up 5 votes
public static void copy(InputStream in, File file) {
	try {
		OutputStream out = new FileOutputStream(file);
		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		out.close();
		in.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 13
Project: PackageSigner2   File: Signer.java   View Source Code Vote up 5 votes
/**
 * Add a copy of the public key to the archive; this should exactly match one
 * of the files in /system/etc/security/otacerts.zip on the device. (The same
 * cert can be extracted from the CERT.RSA file but this is much easier to get
 * at.)
 */
private static void addOTACert(
        JarOutputStream outputJar,
        long timestamp,
        Manifest manifest)
        throws IOException, GeneralSecurityException {
    InputStream input = new ByteArrayInputStream(readKeyContents(PUBLIC_KEY));
    
    BASE64Encoder base64 = new BASE64Encoder();
    MessageDigest md = MessageDigest.getInstance("SHA1");
    
    JarEntry je = new JarEntry(OTACERT_NAME);
    je.setTime(timestamp);
    outputJar.putNextEntry(je);
    
    byte[] b = new byte[4096];
    int read;
    
    System.out.print("\rGenerating OTA certificate...");
    
    while ((read = input.read(b)) != -1) {
        outputJar.write(b, 0, read);
        md.update(b, 0, read);
    }
    input.close();
    
    Attributes attr = new Attributes();
    attr.putValue("SHA1-Digest", base64.encode(md.digest()));
    manifest.getEntries().put(OTACERT_NAME, attr);
}
 
Example 14
Project: FilterPlayer   File: OpenGlUtils.java   View Source Code Vote up 5 votes
private static Bitmap getImageFromAssetsFile(Context context,String fileName){
    Bitmap image = null;
    AssetManager am = context.getResources().getAssets();
    try{
        InputStream is = am.open(fileName);
        image = BitmapFactory.decodeStream(is);
        is.close();
    }catch (IOException e){
        e.printStackTrace();
    }
    return image;
}
 
Example 15
Project: FirefoxData-android   File: FileEntity.java   View Source Code Vote up 5 votes
public void writeTo(final OutputStream outstream) throws IOException {
    Args.notNull(outstream, "Output stream");
    final InputStream instream = new FileInputStream(this.file);
    try {
        final byte[] tmp = new byte[OUTPUT_BUFFER_SIZE];
        int l;
        while ((l = instream.read(tmp)) != -1) {
            outstream.write(tmp, 0, l);
        }
        outstream.flush();
    } finally {
        instream.close();
    }
}
 
Example 16
Project: incubator-netbeans   File: AbstractCommandTestCase.java   View Source Code Vote up 5 votes
protected void assertContents(InputStream is, int contents) throws FileNotFoundException, IOException {        
    try {
        int i = is.read();
        assertEquals(contents, i);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}
 
Example 17
Project: tuxguitar   File: SF2Soundbank.java   View Source Code Vote up 5 votes
public SF2Soundbank(URL url) throws IOException {

        InputStream is = url.openStream();
        try {
            readSoundbank(is);
        } finally {
            is.close();
        }
    }
 
Example 18
Project: openjdk-jdk10   File: PackerImpl.java   View Source Code Vote up 4 votes
void run(JarFile in, OutputStream out) throws IOException {
    List<InFile> inFiles = scanJar(in);

    if (verbose > 0)
        Utils.log.info("Reading " + inFiles.size() + " files...");

    int numDone = 0;
    for (InFile inFile : inFiles) {
        String name      = inFile.name;
        // (5078608) : discount the resource files completely from segmenting
        long inflen = (inFile.isMetaInfFile())
                       ? 0L
                       : inFile.getInputLength() ;
        if ((segmentSize += inflen) > segmentLimit) {
            segmentSize -= inflen;
            // Estimate number of remaining segments:
            float filesDone = numDone+1;
            float segsDone  = segmentCount+1;
            float filesToDo = inFiles.size() - filesDone;
            float segsToDo  = filesToDo * (segsDone/filesDone);
            if (verbose > 1)
                Utils.log.fine("Estimated segments to do: "+segsToDo);
            flushPartial(out, (int) Math.ceil(segsToDo));
        }
        InputStream strm = inFile.getInputStream();
        if (verbose > 1)
            Utils.log.fine("Reading " + name);
        Package.File file = null;
        if (inFile.mustProcess()) {
            file = readClass(name, strm);
            if (file == null) {
                strm.close();
                strm = inFile.getInputStream();
            }
        }
        if (file == null) {
            file = readFile(name, strm);
            pkg.addFile(file);
        }
        inFile.copyTo(file);
        strm.close();  // tidy up
        noteRead(inFile);
        numDone += 1;
    }
    flushAll(out);
}
 
Example 19
Project: openjdk-jdk10   File: B6449504.java   View Source Code Vote up 4 votes
static void readAndClose(InputStream is) throws IOException {
    while (is.read() != -1) ;
    is.close();
}
 
Example 20
Project: faitic-checker   File: Shortcut.java   View Source Code Vote up 3 votes
public static String readFileFromResources(String resource){
    
	StringBuffer textread=new StringBuffer();

	InputStream reader=null;
	
	try{	// Possible file not found

		reader = Shortcut.class.getResourceAsStream("/daraujo/faiticchecker/" + resource);
	
		byte[] buffer=new byte[1000];		// Buffer for reading
		int bytesread=reader.read(buffer);	// Number of bytes read
	
		while(bytesread!=-1){				// If it keeps reading...
		
			textread.append(new String(buffer,0,bytesread,"UTF-8"));	// Read as UTF-8
			bytesread=reader.read(buffer);								// Refresh bytes read
		
		}
		
	} catch(Exception ex){
		
		ex.printStackTrace();
		
	} finally{
		
		try{ if(reader!=null) reader.close(); }			// Close the reader !!
		catch(Exception ex2){ ex2.printStackTrace(); }
		
	}
	
	return textread.toString();
	
}