Java Code Examples for java.io.FileInputStream.available()

The following are Jave code examples for showing how to use available() of the java.io.FileInputStream 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: openjdk-jdk10   File: TestBug4179766.java   View Source Code Vote up 6 votes
/**
 * Get the data from the class file for the specified class.  If
 * the file can't be found, or the class is not one of the
 * special ones listed below, return null.
 *    Bug4179766Class
 *    Bug4179766Resource
 */
private byte[] getClassData(String className) {
    boolean shouldLoad = className.equals("Bug4179766Class");
    shouldLoad = shouldLoad || className.equals("Bug4179766Resource");

    if (shouldLoad) {
        try {
            File file = new File(System.getProperty("test.classes", "."), className+CLASS_SUFFIX);
            FileInputStream fi = new FileInputStream(file);
            byte[] result = new byte[fi.available()];
            fi.read(result);
            return result;
        } catch (Exception e) {
            return null;
        }
    } else {
        return null;
    }
}
 
Example 2
Project: mobiletailchanger   File: MainActivity.java   View Source Code Vote up 6 votes
String fileTxtRead(String fileName)
{  
	String res="";
       try
	{
		File file = new File(fileName);  
		FileInputStream fis = new FileInputStream(file);  
		int length = fis.available(); 
		byte [] buffer = new byte[length]; 
		fis.read(buffer);     
		res = EncodingUtils.getString(buffer, "UTF-8"); 
		fis.close();     
	}
	catch (IOException e)
	{
		e.printStackTrace();
	}  
	return res;
}
 
Example 3
Project: incubator-netbeans   File: TestCatalogModel.java   View Source Code Vote up 6 votes
private Document  getDocument(FileObject fo){
    Document result = null;
    if (documentPooling) {
        result = documentPool().get(fo);
    }
    if (result != null) return result;
    try {
        
        File file = FileUtil.toFile(fo);
        FileInputStream fis = new FileInputStream(file);
        byte buffer[] = new byte[fis.available()];
        result = new org.netbeans.editor.BaseDocument(true, fo.getMIMEType());
        result.remove(0, result.getLength());
        fis.read(buffer);
        fis.close();
        String str = new String(buffer);
        result.insertString(0,str,null);
        
    } catch (Exception dObjEx) {
        return null;
    }
    if (documentPooling) {
        documentPool().put(fo, result);
    }
    return result;
}
 
Example 4
Project: Java-APIs   File: ClassifyBinaryArticlesTest.java   View Source Code Vote up 6 votes
public void testBinary() throws IOException, ClassificationException {
	File file = new File("src/test/resources/data/SampleData.txt");
	FileInputStream fileInputStream = new FileInputStream(file);
	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
	int available;
	while ((available = fileInputStream.available()) > 0) {
		byte[] data = new byte[available];
		fileInputStream.read(data);
		byteArrayOutputStream.write(data);
	}
	fileInputStream.close();
	byteArrayOutputStream.close();

	Result result = classificationClient.getClassifiedDocument(byteArrayOutputStream.toByteArray(), "SampleData.txt");
	assertEquals("Article count", 1, result.getArticles().size());

}
 
Example 5
Project: AppCommonFrame   File: FileUtil.java   View Source Code Vote up 6 votes
/**
 * 通过完整路径读取文件的字节流 . <br>
 * @author liulongzhenhai 2012-8-2 上午8:49:55 <br>
 * @param fileFullPath 读取文件路径
 * @return 返回整个文件数据 流
 */
public static byte[] readFilebyte(final String fileFullPath) {
	final File file = getFileObject(fileFullPath);
	if (file != null && file.exists()) {
		try {
			FileInputStream fis = new FileInputStream(file);
			final int readSize = fis.available();
			final byte[] buff = new byte[readSize];
			fis.read(buff);
			fis.close();
			fis = null;
			return buff;
		} catch (final Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	return null;
}
 
Example 6
Project: qpboc-kata   File: FileUtil.java   View Source Code Vote up 6 votes
public static byte[] readAidFile(String fileName)
{
    byte [] buffer = null;

    try{
        File file = new File(fileName);
        if (!file.exists())
        {
            return null;
        }

        FileInputStream fis = new FileInputStream(file);

        int length = fis.available();
        buffer = new byte[length];
        fis.read(buffer);
        fis.close();
    }
    catch(Exception e){
        e.printStackTrace();
    }

    return buffer;
}
 
Example 7
Project: NotifyTools   File: VcardService.java   View Source Code Vote up 5 votes
public String get(Cursor cursor) {
        //cursor.moveToFirst();
        String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
        Log.d("Vcard lookupKey ", lookupKey);
        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
        Log.d("Vcard uri ", uri.toString());
        AssetFileDescriptor fd;
        try {
            fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");

            // Your Complex Code and you used function without loop so how can you get all Contacts Vcard.??


           /* FileInputStream fis = fd.createInputStream();
            byte[] buf = new byte[(int) fd.getDeclaredLength()];
            fis.read(buf);
            String VCard = new String(buf);
            String path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
            FileOutputStream out = new FileOutputStream(path);
            out.write(VCard.toString().getBytes());
            Log.d("Vcard",  VCard);*/
            //https://stackoverflow.com/questions/42017591/in-android-7-contentresolvers-method-openassetfiledescriptorvcarduri-r-re
            FileInputStream fis = fd.createInputStream();
            byte[] buf = new byte[fis.available()];
            fis.read(buf);
            String vcardstring = new String(buf);
            if(mapVcard.containsKey(uri.toString())){
                String vv=mapVcard.get(uri.toString());
                if(vv.equals(vcardstring)){
                    Log.d("Vcard lookupKey 重复", lookupKey);
                    return vv;
                }
            }

            mapVcard.put(uri.toString(),vcardstring);
            //log.d("write "+vcardstring);
//            FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, true);
            mFileOutputStream.write(buf);//vcardstring.toString().getBytes());
            return vcardstring;

        } catch (Exception e1) {
            e1.printStackTrace();
            log.e(e1);
        }
        return "";
    }
 
Example 8
Project: Java-APIs   File: ClassifyDocumentWithHashTest.java   View Source Code Vote up 5 votes
public void testBinary() throws IOException, ClassificationException {
	File file = new File("src/test/resources/data/SampleData.txt");
	FileInputStream fileInputStream = new FileInputStream(file);
	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
	int available;
	while ((available = fileInputStream.available()) > 0) {
		byte[] data = new byte[available];
		fileInputStream.read(data);
		byteArrayOutputStream.write(data);
	}
	fileInputStream.close();
	byteArrayOutputStream.close();

	Result result1 = classificationClient.getClassifiedDocument(byteArrayOutputStream.toByteArray(), "SampleData.txt");
	assertEquals("Hash 1", "f7be152b1d057570b892dbe3dc39bd70", result1.getHash());

	Map<String, Collection<String>> metadata = new HashMap<String, Collection<String>>();
	Collection<String> cheeses = new Vector<String>();
	cheeses.add("Brie");
	cheeses.add("Camenbert");
	cheeses.add("Cheddar");
	metadata.put("cheeses", cheeses);

	Result result2 = classificationClient.getClassifiedDocument(byteArrayOutputStream.toByteArray(), "SampleData.txt", new Title("title"), metadata);
	assertEquals("Hash 2", "c723555e774c94d0ead71d5c1cc06efc", result2.getHash());

}
 
Example 9
Project: VirtualHook   File: AtomicFile.java   View Source Code Vote up 5 votes
/**
 * A convenience for {@link #openRead()} that also reads all of the
 * file contents into a byte array which is returned.
 */
public byte[] readFully() throws IOException {
    FileInputStream stream = openRead();
    try {
        int pos = 0;
        int avail = stream.available();
        byte[] data = new byte[avail];
        while (true) {
            int amt = stream.read(data, pos, data.length-pos);
            //Log.i("foo", "Read " + amt + " bytes at " + pos
            //        + " of avail " + data.length);
            if (amt <= 0) {
                //Log.i("foo", "**** FINISHED READING: pos=" + pos
                //        + " len=" + data.length);
                return data;
            }
            pos += amt;
            avail = stream.available();
            if (avail > data.length-pos) {
                byte[] newData = new byte[pos+avail];
                System.arraycopy(data, 0, newData, 0, pos);
                data = newData;
            }
        }
    } finally {
        stream.close();
    }
}
 
Example 10
Project: incubator-netbeans   File: TestCatalogModel.java   View Source Code Vote up 5 votes
private Document  getDocument(FileObject fo){
    Document result = null;
    if (documentPooling) {
        result = documentPool().get(fo);
    }
    if (result != null) return result;
    try {
        
        File file = FileUtil.toFile(fo);
        FileInputStream fis = new FileInputStream(file);
        byte buffer[] = new byte[fis.available()];
        result = new org.netbeans.editor.BaseDocument(
                org.netbeans.modules.xml.text.syntax.XMLKit.class, false);
        result.remove(0, result.getLength());
        fis.read(buffer);
        fis.close();
        String str = new String(buffer);
        result.insertString(0,str,null);
        
    } catch (Exception dObjEx) {
        return null;
    }
    if (documentPooling) {
        documentPool().put(fo, result);
    }
    return result;
}
 
Example 11
Project: incubator-netbeans   File: TestCatalogModel.java   View Source Code Vote up 5 votes
private Document  getDocument(FileObject fo){
    Document result = null;
    if (documentPooling) {
        result = documentPool().get(fo);
    }
    if (result != null) return result;
    try {
        
        File file = FileUtil.toFile(fo);
        FileInputStream fis = new FileInputStream(file);
        byte buffer[] = new byte[fis.available()];
        result = new org.netbeans.editor.BaseDocument(
                org.netbeans.modules.xml.text.syntax.XMLKit.class, false);
        result.remove(0, result.getLength());
        fis.read(buffer);
        fis.close();
        String str = new String(buffer);
        result.insertString(0,str,null);
        
    } catch (Exception dObjEx) {
        return null;
    }
    if (documentPooling) {
        documentPool().put(fo, result);
    }
    return result;
}
 
Example 12
Project: Java-APIs   File: ClassifyLargeTest.java   View Source Code Vote up 5 votes
public void testBinary() throws IOException, ClassificationException {

		URL log4jXmlUrl = ClassLoader.getSystemResource("log4j.xml");
		if (log4jXmlUrl != null) System.out.println(log4jXmlUrl.toExternalForm());
		File file = new File("src/test/resources/data/SampleData.txt");
		FileInputStream fileInputStream = new FileInputStream(file);
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		int available;
		while ((available = fileInputStream.available()) > 0) {
			byte[] data = new byte[available];
			fileInputStream.read(data);
			byteArrayOutputStream.write(data);
		}
		fileInputStream.close();
		byteArrayOutputStream.close();

		classificationClient.getClassificationConfiguration().setConnectionTimeoutMS(0);
		classificationClient.getClassificationConfiguration().setSocketTimeoutMS(0);

		try {
			Date startDate = new Date();
			classificationClient.getClassifiedDocument(byteArrayOutputStream.toByteArray(), "SampleData.txt");
			Date endDate = new Date();
			assertTrue("Classification took too long: " + (endDate.getTime() - startDate.getTime()) + "ms", (endDate.getTime() - startDate.getTime()) < 100000);
		} catch (Exception e) {
			fail("ClassifyLargeTest failure: " + e.getMessage());
		}

	}
 
Example 13
Project: Transwarp-Sample-Code   File: FileUtil.java   View Source Code Vote up 5 votes
/**
 * file转byte
 * @param file 文件名
 * @return byte文件
 * @throws Exception 文件为空
 */
public static byte[] file2Byte(File file) throws Exception {
    FileInputStream fileInputStream = new FileInputStream(file);
    byte[] data = new byte[fileInputStream.available()];
    fileInputStream.read(data);
    fileInputStream.close();
    return data;
}
 
Example 14
Project: ChronoBike   File: ClassDynLoader.java   View Source Code Vote up 5 votes
protected byte[] getClassFileBytes(String className) 
{
	byte result[] = null;
   	
	if(m_bCanLoadClass)
	{
		String clpack = className.replace('.', '/') ;
 	    for(int n=0; n<m_arrPaths.size(); n++)
    	{
 	    	String csPath = m_arrPaths.get(n);
	    	try 
	    	{
	    		FileInputStream fi = new FileInputStream(csPath + clpack + ".class");
	    	    result = new byte[fi.available()];
	    	    fi.read(result);
	    	    fi.close() ;
	    	    return result;
	    	} 
	    	catch (Exception e) 
	    	{	
	    	}
    	}
	}

	if(m_bCanLoadJar && m_jarEntries != null)
	{
		result = m_jarEntries.loadJarEntry(className);
	}
	return result;
}
 
Example 15
Project: JarShrink   File: Files.java   View Source Code Vote up 5 votes
public static int getSize(File file) {
	
	int filesize = -1;
	boolean stream = false;
	
	try {
		FileInputStream fis = new FileInputStream(file);
		filesize = fis.available();
		filesize /= 1024;
		fis.close();
	} catch (Exception e) { e.printStackTrace(); }
	
	return filesize;
}
 
Example 16
Project: PlusGram   File: ContentDataSource.java   View Source Code Vote up 5 votes
@Override
public long open(DataSpec dataSpec) throws ContentDataSourceException {
  try {
    uriString = dataSpec.uri.toString();
    AssetFileDescriptor assetFd = resolver.openAssetFileDescriptor(dataSpec.uri, "r");
    inputStream = new FileInputStream(assetFd.getFileDescriptor());
    long skipped = inputStream.skip(dataSpec.position);
    if (skipped < dataSpec.position) {
      // We expect the skip to be satisfied in full. If it isn't then we're probably trying to
      // skip beyond the end of the data.
      throw new EOFException();
    }
    if (dataSpec.length != C.LENGTH_UNBOUNDED) {
      bytesRemaining = dataSpec.length;
    } else {
      bytesRemaining = inputStream.available();
      if (bytesRemaining == 0) {
        // FileInputStream.available() returns 0 if the remaining length cannot be determined, or
        // if it's greater than Integer.MAX_VALUE. We don't know the true length in either case,
        // so treat as unbounded.
        bytesRemaining = C.LENGTH_UNBOUNDED;
      }
    }
  } catch (IOException e) {
    throw new ContentDataSourceException(e);
  }

  opened = true;
  if (listener != null) {
    listener.onTransferStart();
  }

  return bytesRemaining;
}
 
Example 17
Project: NICON   File: PrintPdf.java   View Source Code Vote up 5 votes
public PrintPdf(String directorio, String fixeiro, double margem, double width, double heigt,String nomeImpressora, int OrientacaoPapel) throws IOException, PrinterException {
    PrintPdf.margin = margem;
    PrintPdf.getWidth = width;
    PrintPdf.getHeight = heigt;
    orientacao=OrientacaoPapel;
    FileInputStream inputStream = new FileInputStream(directorio);
    
    byte[] pdfContent = new byte[inputStream.available()];
    inputStream.read( pdfContent, 0, inputStream.available());
    initialize(pdfContent, fixeiro, nomeImpressora);
}
 
Example 18
Project: MiniThunder   File: XLLogInternal.java   View Source Code Vote up 5 votes
private long getLogFileSize() {
    long j = -1;
    if (this.mFile == null) {
        return -1;
    }
    try {
        FileInputStream fileInputStream = new FileInputStream(this.mFile);
        j = (long) fileInputStream.available();
        fileInputStream.close();
        return j;
    } catch (Exception e) {
        return j;
    }
}
 
Example 19
Project: Android-Practice   File: MainActivity.java   View Source Code Vote up 4 votes
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<String> arData = new ArrayList<String>();
    mAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, arData);
    ListView list = (ListView)findViewById(R.id.logList);
    mAdapter.add("ssss");
    list.setAdapter(mAdapter);

    try {
        FileInputStream fis = openFileInput("MousePos.txt");
        FileChannel inChannel = fis.getChannel();

        final int s = fis.available();
        ByteBuffer buff = ByteBuffer.allocate((int)fis.available());
        buff.clear();

        inChannel.read(buff);

        buff.rewind();

        final int posSize = s/4;
        float[] pos = new float[posSize];
        buff.asFloatBuffer().get(pos);

        inChannel.close();

        for (int i=0; i < posSize; i+=2)
        {
            mAdapter.add("" + pos[i] + ", " + pos[i+1]);
        }

        fis.close();
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }

    list.setOnTouchListener(this);
}
 
Example 20
Project: directory-mavibot   File: BulkLoader.java   View Source Code Vote up 4 votes
private static <K, V> Tuple<K, Set<V>> fetchTuple( BTree<K, V> btree, FileInputStream fis )
{
    try
    {
        if ( fis.available() == 0 )
        {
            return null;
        }

        Tuple<K, Set<V>> tuple = new Tuple<K, Set<V>>();
        tuple.value = new TreeSet<V>();

        byte[] intBytes = new byte[4];

        // Read the key length
        fis.read( intBytes );
        int keyLength = IntSerializer.deserialize( intBytes );

        // Read the key
        byte[] keyBytes = new byte[keyLength];
        fis.read( keyBytes );
        K key = btree.getKeySerializer().fromBytes( keyBytes );
        tuple.key = key;

        // get the number of values
        fis.read( intBytes );
        int nbValues = IntSerializer.deserialize( intBytes );

        // Serialize the values
        for ( int i = 0; i < nbValues; i++ )
        {
            // Read the value length
            fis.read( intBytes );
            int valueLength = IntSerializer.deserialize( intBytes );

            // Read the value
            byte[] valueBytes = new byte[valueLength];
            fis.read( valueBytes );
            V value = btree.getValueSerializer().fromBytes( valueBytes );
            tuple.value.add( value );
        }

        return tuple;
    }
    catch ( IOException ioe )
    {
        return null;
    }
}