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

The following examples show how to use java.io.FileInputStream#available() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EncodingResolver.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
private static String getRCEncoding(String fileName) {
	try {
		FileInputStream input = new FileInputStream(fileName);
		// read 4K bytes
		int read = 4096;
		if (input.available() < read){
			read = input.available();
		}
		byte[] bytes = new byte[read];
		input.read(bytes);
		input.close();
		String content = new String(bytes);

		if (content.indexOf("code_page(") != -1) { //$NON-NLS-1$
			String code = content.substring(content.indexOf("code_page(")+10); //$NON-NLS-1$
			code = code.substring(0,code.indexOf(")")); //$NON-NLS-1$
			return RTF2JavaEncoding(code);
		}
	} catch(Exception e) {
		return null;
	}
	return null;
}
 
Example 2
Source File: Loader2.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
protected Class findClass2(String name) throws ClassNotFoundException {
  print("Fetching the implementation of "+name);
  int old = _recur;
  try {
    FileInputStream fi = new FileInputStream(name+".impl2");
    byte result[] = new byte[fi.available()];
    fi.read(result);

    print("DefineClass1 on "+name);
    _recur++;
    Class clazz = defineClass(name, result, 0, result.length);
    _recur = old;
    print("Returning newly loaded class.");
    return clazz;
  } catch (Exception e) {
    _recur = old;
    print("Not found on disk.");
    // If we caught an exception, either the class was not found or
    // it was unreadable by our process.
    return null;
    //throw new ClassNotFoundException(e.toString());
  }
}
 
Example 3
Source File: NegativeAvailable.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 *  Skip toSkip number of bytes and return the remaining bytes of the file.
 */
private static long skipBytes(FileInputStream fis, int toSkip, long space)
        throws IOException {
    long skip = fis.skip(toSkip);
    if (skip != toSkip) {
        throw new RuntimeException("skip() returns " + skip
                                   + " but expected " + toSkip);
    }
    long newSpace = space - toSkip;
    long remaining = newSpace > 0 ? newSpace : 0;
    int avail = fis.available();
    if (avail != remaining) {
        throw new RuntimeException("available() returns " + avail
                                   + " but expected " + remaining);
    }

    System.out.println("Skipped " + skip + " bytes "
                       + " available() returns " + avail);
    return newSpace;
}
 
Example 4
Source File: Loader2.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
protected Class findClass2(String name) throws ClassNotFoundException {
  print("Fetching the implementation of "+name);
  int old = _recur;
  try {
    FileInputStream fi = new FileInputStream(name+".impl2");
    byte result[] = new byte[fi.available()];
    fi.read(result);

    print("DefineClass1 on "+name);
    _recur++;
    Class clazz = defineClass(name, result, 0, result.length);
    _recur = old;
    print("Returning newly loaded class.");
    return clazz;
  } catch (Exception e) {
    _recur = old;
    print("Not found on disk.");
    // If we caught an exception, either the class was not found or
    // it was unreadable by our process.
    return null;
    //throw new ClassNotFoundException(e.toString());
  }
}
 
Example 5
Source File: ControllerUtils.java    From efo with MIT License 6 votes vote down vote up
/**
 * 加载本地资源
 *
 * @param response 返回的Response
 * @param path 资源路径
 * @param download 直接下载
 */
public static void loadResource(HttpServletResponse response, String path, boolean download) throws IOException {
    if (Checker.isNotEmpty(path)) {
        File file = new File(path);
        if (download) {
            setResponseFileName(response, file.getName());
        }
        FileInputStream in = new FileInputStream(file);
        ServletOutputStream os = response.getOutputStream();
        byte[] b;
        while (in.available() > 0) {
            b = in.available() > 1024 ? new byte[1024] : new byte[in.available()];
            in.read(b, 0, b.length);
            os.write(b, 0, b.length);
        }
        in.close();
        os.flush();
        os.close();
    } else {
        response.sendRedirect(DefaultValues.NOT_FOUND_PAGE);
    }
}
 
Example 6
Source File: FileUtils.java    From frpc-Android with Apache License 2.0 6 votes vote down vote up
public static String readDataFromFile(String fileName) {
	String res = null;
	try {
		File f = new File(cachePath + fileName);
		if (!f.exists()) {
			return null;
		}
		FileInputStream fin = new FileInputStream(f);
		int length = fin.available();
		if (length > 0) {
			byte[] buffer = new byte[length];
			fin.read(buffer);
			res = new String(buffer, "utf-8");
		}
		fin.close();
	} catch (Exception e) {
		e.printStackTrace();
		LogUtils.PST(e);
	}
	return res;
}
 
Example 7
Source File: Loader2.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
protected Class findClass2(String name) throws ClassNotFoundException {
  print("Fetching the implementation of "+name);
  int old = _recur;
  try {
    FileInputStream fi = new FileInputStream(name+".impl2");
    byte result[] = new byte[fi.available()];
    fi.read(result);

    print("DefineClass1 on "+name);
    _recur++;
    Class clazz = defineClass(name, result, 0, result.length);
    _recur = old;
    print("Returning newly loaded class.");
    return clazz;
  } catch (Exception e) {
    _recur = old;
    print("Not found on disk.");
    // If we caught an exception, either the class was not found or
    // it was unreadable by our process.
    return null;
    //throw new ClassNotFoundException(e.toString());
  }
}
 
Example 8
Source File: FileUtils.java    From MyTv with Apache License 2.0 6 votes vote down vote up
/**
 * 读取本地文件,传统IO
 * 
 * @param filePath
 *            文件路径
 * @throws FileNotFoundException
 * @throws IOException
 * @return
 */
public static byte[] read(String filePath) throws IOException,
		FileNotFoundException {
	if (filePath == null) {
		return null;
	}
	FileInputStream fis = new FileInputStream(new File(filePath));
	int size = fis.available();
	ByteArrayOutputStream baos = new ByteArrayOutputStream(size);
	byte[] data = null;
	if (size < BUFFER_SIZE) {
		data = new byte[size];
	} else {
		data = new byte[BUFFER_SIZE];
	}
	while (true) {
		int count = fis.read(data);
		if (count == -1) {
			break;
		}
		baos.write(data);
	}
	fis.close();
	return baos.toByteArray();
}
 
Example 9
Source File: EncodingResolver.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
private static String getRCEncoding(String fileName) {
	try {
		FileInputStream input = new FileInputStream(fileName);
		// read 4K bytes
		int read = 4096;
		if (input.available() < read) {
			read = input.available();
		}
		byte[] bytes = new byte[read];
		input.read(bytes);
		input.close();
		String content = new String(bytes);

		if (content.indexOf("code_page(") != -1) { //$NON-NLS-1$
			String code = content.substring(content.indexOf("code_page(") + 10); //$NON-NLS-1$
			code = code.substring(0, code.indexOf(")")); //$NON-NLS-1$
			return RTF2JavaEncoding(code);
		}
	} catch (Exception e) {
		return null;
	}
	return null;
}
 
Example 10
Source File: LedgerTransportTEEProxy.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
public byte[] loadNVM(String nvmFile) {
	try {
		FileInputStream in = context.openFileInput(nvmFile);
		byte[] nvm = new byte[in.available()];
		in.read(nvm);
		return nvm;
	}
	catch(Exception e) {
		if (e instanceof FileNotFoundException) {
			Log.d(TAG, "Unable to load NVM");
		}
		else {
			Log.d(TAG, "Unable to load NVM", e);
		}
		return null;
	}
}
 
Example 11
Source File: RSAAsymetricCrypto.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static PublicKey loadPublicKey(String fileName) throws Exception {
   FileInputStream fis = new FileInputStream(fileName);
   int numBtyes = fis.available();
   byte[] bytes = new byte[numBtyes];
   fis.read(bytes);
   fis.close();

   KeyFactory keyFactory = KeyFactory.getInstance("RSA");
   KeySpec keySpec = new X509EncodedKeySpec(bytes);
   PublicKey keyFromBytes = keyFactory.generatePublic(keySpec);
   return keyFromBytes;
}
 
Example 12
Source File: TestCatalogModel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 13
Source File: ContentDataSource.java    From K-Sonic with MIT License 5 votes vote down vote up
@Override
public long open(DataSpec dataSpec) throws ContentDataSourceException {
  try {
    uri = dataSpec.uri;
    assetFileDescriptor = resolver.openAssetFileDescriptor(uri, "r");
    inputStream = new FileInputStream(assetFileDescriptor.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_UNSET) {
      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_UNSET;
      }
    }
  } catch (IOException e) {
    throw new ContentDataSourceException(e);
  }

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

  return bytesRemaining;
}
 
Example 14
Source File: ToolsHelper.java    From org.hl7.fhir.core with 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 15
Source File: AtomicFile.java    From container with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 16
Source File: Solution.java    From JavaRushTasks with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {

        Scanner scan = new Scanner(System.in);
        String fileName1 = scan.nextLine();
        String fileName2 = scan.nextLine();
        String fileName3 = scan.nextLine();

        FileInputStream f1 = new FileInputStream(fileName1);
        FileOutputStream f2 = new FileOutputStream(fileName2);
        FileOutputStream f3 = new FileOutputStream(fileName3);

        int fileSize = f1.available();
        int part1Size = fileSize % 2 == 0 ? fileSize / 2 : fileSize / 2 + 1;

        while (f1.available() > 0) {
            byte[] buf1 = new byte [part1Size];
            byte[] buf2 = new byte [fileSize - part1Size];

            f1.read(buf1);
            f1.read(buf2);
            f2.write(buf1);
            f3.write(buf2);
        }
        f1.close ();
        f2.close ();
        f3.close ();
    }
 
Example 17
Source File: ResourceManager.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * displays a web page describing the service
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/html");
    ServletOutputStream outStream = response.getOutputStream();
    String fileName = System.getenv("CATALINA_HOME") +
            "/webapps/resourceService/welcome.htm";

    // convert htm file to a byte array
    if (new File(fileName).exists()) {
        FileInputStream fStream = new FileInputStream(fileName);
        byte[] b = new byte[fStream.available()];
        fStream.read(b);
        fStream.close();

        // load the full welcome page if possible
        outStream.write(b);
    }
    else {
        // otherwise load a boring default
        StringBuilder output = new StringBuilder();
        output.append("<html><head><title>YAWL Resource Service</title>")
                .append("</head><body><H3>Welcome to the YAWL Resource Service")
                .append("</H3></body></html>");
        outStream.print(output.toString());
    }
    outStream.flush();
    outStream.close();
}
 
Example 18
Source File: Solution.java    From JavaExercises with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    int countSpaces = 0;
    FileInputStream file = new FileInputStream(args[0]);
    int countChars = file.available();
    while (file.available() > 0) {
        if ((byte) file.read() == ' ')
            countSpaces++;
    }
    file.close();
    System.out.printf("%.2f", (double) countSpaces/countChars*100);
}
 
Example 19
Source File: HexDump.java    From mpxj with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This method opens the input and output files and kicks
 * off the processing.
 *
 * @param input Name of the input file
 * @param output Name of the output file
 * @throws Exception Thrown on file read errors
 */
private static void process(String input, String output) throws Exception
{
   FileInputStream is = new FileInputStream(input);
   PrintWriter pw = new PrintWriter(new FileWriter(output));

   byte[] buffer = new byte[is.available()];
   is.read(buffer);
   pw.println(ByteArrayHelper.hexdump(buffer, 0, buffer.length, true, 16, ""));

   is.close();
   pw.flush();
   pw.close();
}
 
Example 20
Source File: MainActivity.java    From qplayer-sdk with MIT License 4 votes vote down vote up
public void fillVideoData () {
    Thread thread = new Thread(){
        public void run() {
            String strFile = "/sdcard/00Files/video.dat";
            try {
                File file = new File(strFile);
                FileInputStream input = new FileInputStream(file);
                int nFileSize = input.available();
                int nFilePos = 0;
                int nDataSize = 0;
                int nRC = 0;
                byte[]  byDataInfo = new byte[16];
                byte[]  byDataBuff = new byte[1024000];

                ByteBuffer byBuff = ByteBuffer.wrap(byDataInfo);

                while (nFilePos < nFileSize) {
                    input.read (byDataInfo, 0, 16);
                    nFilePos += 16;

                    nDataSize = byBuff.getInt(0);

                    input.read (byDataBuff, 0, nDataSize);
                    nFilePos += nDataSize;

                    nRC = -1;
                    while (nRC != 0) {
                        nRC = m_Player.SetParam(BasePlayer.QCPLAY_PID_EXT_SOURCE_INFO, 2, byDataInfo);
                    }
                    nRC = -1;
                    while (nRC != 0) {
                        nRC = m_Player.SetParam(BasePlayer.QCPLAY_PID_EXT_SOURCE_DATA, 2, byDataBuff);
                    }
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    thread.start();
}