下面列出了java.io.BufferedInputStream#available ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void extractZipEntry(ZipFile zf, ZipEntry zipEntry, File dir) throws Exception {
File destFile = new File(dir, zipEntry.getName());
if (zipEntry.isDirectory())
destFile.mkdirs();
else {
destFile.getParentFile().mkdirs();
destFile.createNewFile();
BufferedInputStream bis = new BufferedInputStream(zf.getInputStream(zipEntry));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(dir, zipEntry.getName())));
long available = bis.available();
long red = 0;
byte[] block;
while (red < available) {
block = new byte[8192];
int readNow = bis.read(block);
bos.write(block, 0, readNow);
red += readNow;
}
bis.close();
bos.flush();
bos.close();
}
}
public static void main(String[] args) throws Exception {
byte[] buffer = new byte[100];
ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
BufferedInputStream bis = new BufferedInputStream(bais, 50);
byte[] smallBuf = new byte[10];
bis.read(smallBuf);
long available = bis.available();
int request = 50;
long s = bis.skip(request);
if (s < available && s < request) {
System.out.println("Skipped fewer bytes than requested and fewer bytes than available");
System.out.println("Available: " + available);
System.out.println("Requested: " + request);
System.out.println("Skipped: " + s);
}
}
public static List<Object> getRowObjectsOnly(String fileName) throws FileNotFoundException, IOException, ClassNotFoundException {
File fileRows = new File(fileName + ".rows.ser");
List<Object> objects = new ArrayList<Object>();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileRows));
ObjectInputStream ois = new ObjectInputStream(bis);
while (bis.available() > 0) {
objects.add(ois.readObject());
}
bis.close();
ois.close();
return objects;
}
private byte[] readResource(String className, String suffix) throws IOException {
// Note to the unwary -- "/" works on Windows, leave it alone.
String fileName = className.replace('.', '/') + "." + suffix;
InputStream origStream = getResourceAsStream(fileName);
if (origStream == null) {
throw new IOException("Resource not found : " + fileName);
}
BufferedInputStream stream = new java.io.BufferedInputStream(origStream);
byte[] data = new byte[stream.available()];
int how_many = stream.read(data);
// Really ought to deal with the corner cases of stream.available()
return data;
}
private byte[] readResource(String className, String suffix) throws IOException {
// Note to the unwary -- "/" works on Windows, leave it alone.
String fileName = className.replace('.', '/') + "." + suffix;
InputStream origStream = getResourceAsStream(fileName);
if (origStream == null) {
throw new IOException("Resource not found : " + fileName);
}
BufferedInputStream stream = new java.io.BufferedInputStream(origStream);
byte[] data = new byte[stream.available()];
int how_many = stream.read(data);
// Really ought to deal with the corner cases of stream.available()
return data;
}
private byte[] readResource(String className, String suffix) throws IOException {
// Note to the unwary -- "/" works on Windows, leave it alone.
String fileName = className.replace('.', '/') + "." + suffix;
InputStream origStream = getResourceAsStream(fileName);
if (origStream == null) {
throw new IOException("Resource not found : " + fileName);
}
BufferedInputStream stream = new java.io.BufferedInputStream(origStream);
byte[] data = new byte[stream.available()];
int how_many = stream.read(data);
// Really ought to deal with the corner cases of stream.available()
return data;
}
@Override
public ImageEntity getBitmap(String key) {
ImageEntity imageEntity = mMemoryCache.getMemCache(key);
if ( imageEntity != null ) {
return imageEntity;
}
DiskLruCache.Snapshot snapshot = null;
try {
snapshot = mDiskCache.get( key );
if ( snapshot == null ) {
return null;
}
final InputStream in = snapshot.getInputStream(0);
if ( in != null ) {
final BufferedInputStream buffIn = new BufferedInputStream(in, IO_BUFFER_SIZE);
int size = buffIn.available();
byte[] bytes = new byte[size];
if ( buffIn.read(bytes) == -1) return null;
imageEntity = saveToMemory(key, bytes);
}
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( snapshot != null ) {
snapshot.close();
}
}
return imageEntity;
}
private byte[] readResource(String className, String suffix) throws IOException {
// Note to the unwary -- "/" works on Windows, leave it alone.
String fileName = className.replace('.', '/') + "." + suffix;
InputStream origStream = getResourceAsStream(fileName);
if (origStream == null) {
throw new IOException("Resource not found : " + fileName);
}
BufferedInputStream stream = new java.io.BufferedInputStream(origStream);
byte[] data = new byte[stream.available()];
int how_many = stream.read(data);
// Really ought to deal with the corner cases of stream.available()
return data;
}
private byte[] readResource(String className, String suffix) throws IOException {
// Note to the unwary -- "/" works on Windows, leave it alone.
String fileName = className.replace('.', '/') + "." + suffix;
InputStream origStream = getResourceAsStream(fileName);
if (origStream == null) {
throw new IOException("Resource not found : " + fileName);
}
BufferedInputStream stream = new java.io.BufferedInputStream(origStream);
byte[] data = new byte[stream.available()];
int how_many = stream.read(data);
// Really ought to deal with the corner cases of stream.available()
return data;
}
public Double genericV8Test(final String benchmark, final String testPath) throws Throwable {
System.out.println("genericV8Test");
if (!checkV8Presence()) {
return null;
}
final String v8shell = System.getProperty("v8.shell.full.path");
final PrintStream systemOut = System.out;
try {
final Process process = Runtime.getRuntime().exec(v8shell + " " + testPath);
process.waitFor();
final InputStream processOut = process.getInputStream();
final BufferedInputStream bis = new BufferedInputStream(processOut);
final byte[] output = new byte[bis.available()];
bis.read(output, 0, bis.available());
final List<String> result = outputToStrings(output);
return filterBenchmark(result, benchmark);
} catch (final Throwable e) {
System.setOut(systemOut);
e.printStackTrace();
throw e;
}
}
private void loadColumnObjects(String fileName) throws FileNotFoundException, IOException {
colObjects = new ArrayList<U>(nrCols);
File fileCols = new File(fileName + ".columns.ser");
// File fileCols = new File(fileName + ".columns.gson");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileCols));
ObjectInputStream ois = new ObjectInputStream(bis);
// TextFile tf = new TextFile(fileName + ".rows.gson", false);
// String line;
// Type type = new TypeToken<T>() {
// }.getType(); // workaround for generics
// Gson gson = new Gson();
// while ((line = tf.readLine()) != null) {
// T fromJson = gson.fromJson(line, type);
// rowObjects.add(fromJson);
// }
// tf.close();
try {
while (bis.available() > 0) {
colObjects.add((U) ois.readObject());
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(DoubleMatrixDataset.class.getName()).log(Level.SEVERE, "Error with column objects", ex);
ex.printStackTrace();
}
bis.close();
ois.close();
if (colObjects.size() != nrCols) {
throw new IOException("The number of column objects in " + fileCols.getName() + " doesn't match the number of columns in " + fileName + ".dat");
}
}
public Double genericV8Test(final String benchmark, final String testPath) throws Throwable {
System.out.println("genericV8Test");
if (!checkV8Presence()) {
return null;
}
final String v8shell = System.getProperty("v8.shell.full.path");
final PrintStream systemOut = System.out;
try {
final Process process = Runtime.getRuntime().exec(v8shell + " " + testPath);
process.waitFor();
final InputStream processOut = process.getInputStream();
final BufferedInputStream bis = new BufferedInputStream(processOut);
final byte[] output = new byte[bis.available()];
bis.read(output, 0, bis.available());
final List<String> result = outputToStrings(output);
return filterBenchmark(result, benchmark);
} catch (final Throwable e) {
System.setOut(systemOut);
e.printStackTrace();
throw e;
}
}
private byte[] readResource(String className, String suffix) throws IOException {
// Note to the unwary -- "/" works on Windows, leave it alone.
String fileName = className.replace('.', '/') + "." + suffix;
InputStream origStream = getResourceAsStream(fileName);
if (origStream == null) {
throw new IOException("Resource not found : " + fileName);
}
BufferedInputStream stream = new java.io.BufferedInputStream(origStream);
byte[] data = new byte[stream.available()];
int how_many = stream.read(data);
// Really ought to deal with the corner cases of stream.available()
return data;
}
private byte[] readResource(String className, String suffix) throws IOException {
// Note to the unwary -- "/" works on Windows, leave it alone.
String fileName = className.replace('.', '/') + "." + suffix;
InputStream origStream = getResourceAsStream(fileName);
if (origStream == null) {
throw new IOException("Resource not found : " + fileName);
}
BufferedInputStream stream = new java.io.BufferedInputStream(origStream);
byte[] data = new byte[stream.available()];
int how_many = stream.read(data);
// Really ought to deal with the corner cases of stream.available()
return data;
}
public Double genericV8Test(final String benchmark, final String testPath) throws Throwable {
System.out.println("genericV8Test");
if (!checkV8Presence()) {
return null;
}
final String v8shell = System.getProperty("v8.shell.full.path");
final PrintStream systemOut = System.out;
try {
final Process process = Runtime.getRuntime().exec(v8shell + " " + testPath);
process.waitFor();
final InputStream processOut = process.getInputStream();
final BufferedInputStream bis = new BufferedInputStream(processOut);
final byte[] output = new byte[bis.available()];
bis.read(output, 0, bis.available());
final List<String> result = outputToStrings(output);
return filterBenchmark(result, benchmark);
} catch (final Throwable e) {
System.setOut(systemOut);
e.printStackTrace();
throw e;
}
}
private void loadOptions( String fileName ) {
try {
BufferedInputStream bis =
new BufferedInputStream( new FileInputStream( fileName ));
int numBytes = bis.available();
byte byteData[] = new byte[ numBytes ];
bis.read( byteData, 0, numBytes );
bis.close();
if ( numBytes < 2 ||
(byteData[0] != (byte) 0xFE || byteData[1] != (byte) 0xFF) )
throw new Exception( "Not a Font2DTest options file" );
String options = new String( byteData, "UTF-16" );
StringTokenizer perLine = new StringTokenizer( options, "\n" );
String title = perLine.nextToken();
if ( !title.equals( "Font2DTest Option File" ))
throw new Exception( "Not a Font2DTest options file" );
/// Parse all options
boolean displayGridOpt = Boolean.parseBoolean( perLine.nextToken() );
boolean force16ColsOpt = Boolean.parseBoolean( perLine.nextToken() );
boolean showFontInfoOpt = Boolean.parseBoolean( perLine.nextToken() );
String rangeNameOpt = perLine.nextToken();
int rangeStartOpt = Integer.parseInt( perLine.nextToken() );
int rangeEndOpt = Integer.parseInt( perLine.nextToken() );
String fontNameOpt = perLine.nextToken();
float fontSizeOpt = Float.parseFloat( perLine.nextToken() );
int fontStyleOpt = Integer.parseInt( perLine.nextToken() );
int fontTransformOpt = Integer.parseInt( perLine.nextToken() );
int g2TransformOpt = Integer.parseInt( perLine.nextToken() );
int textToUseOpt = Integer.parseInt( perLine.nextToken() );
int drawMethodOpt = Integer.parseInt( perLine.nextToken() );
int antialiasOpt = Integer.parseInt(perLine.nextToken());
int fractionalOpt = Integer.parseInt(perLine.nextToken());
int lcdContrast = Integer.parseInt(perLine.nextToken());
String userTextOpt[] = { "Font2DTest!" };
String dialogEntry = "Font2DTest!";
if (textToUseOpt == fp.USER_TEXT ) {
int numLines = perLine.countTokens(), lineNumber = 0;
if ( numLines != 0 ) {
userTextOpt = new String[ numLines ];
dialogEntry = "";
for ( ; perLine.hasMoreElements(); lineNumber++ ) {
userTextOpt[ lineNumber ] = perLine.nextToken();
dialogEntry += userTextOpt[ lineNumber ] + "\n";
}
}
}
/// Reset GUIs
displayGridCBMI.setState( displayGridOpt );
force16ColsCBMI.setState( force16ColsOpt );
showFontInfoCBMI.setState( showFontInfoOpt );
rm.setSelectedRange( rangeNameOpt, rangeStartOpt, rangeEndOpt );
fontMenu.setSelectedItem( fontNameOpt );
sizeField.setText( String.valueOf( fontSizeOpt ));
styleMenu.setSelectedIndex( fontStyleOpt );
transformMenu.setSelectedIndex( fontTransformOpt );
transformMenuG2.setSelectedIndex( g2TransformOpt );
textMenu.setSelectedIndex( textToUseOpt );
methodsMenu.setSelectedIndex( drawMethodOpt );
antiAliasMenu.setSelectedIndex( antialiasOpt );
fracMetricsMenu.setSelectedIndex( fractionalOpt );
contrastSlider.setValue(lcdContrast);
userTextArea.setText( dialogEntry );
updateGUI();
if ( textToUseOpt == fp.FILE_TEXT ) {
tFileName = perLine.nextToken();
readTextFile(tFileName );
}
/// Reset option variables and repaint
fp.loadOptions( displayGridOpt, force16ColsOpt,
rangeStartOpt, rangeEndOpt,
fontNameOpt, fontSizeOpt,
fontStyleOpt, fontTransformOpt, g2TransformOpt,
textToUseOpt, drawMethodOpt,
antialiasOpt, fractionalOpt,
lcdContrast, userTextOpt );
if ( showFontInfoOpt ) {
fireUpdateFontInfo();
fontInfoDialog.show();
}
else
fontInfoDialog.hide();
}
catch ( Exception ex ) {
fireChangeStatus( "ERROR: Failed to Load Options File; See Stack Trace", true );
ex.printStackTrace();
}
}
private void loadOptions( String fileName ) {
try {
BufferedInputStream bis =
new BufferedInputStream( new FileInputStream( fileName ));
int numBytes = bis.available();
byte byteData[] = new byte[ numBytes ];
bis.read( byteData, 0, numBytes );
bis.close();
if ( numBytes < 2 ||
(byteData[0] != (byte) 0xFE || byteData[1] != (byte) 0xFF) )
throw new Exception( "Not a Font2DTest options file" );
String options = new String( byteData, "UTF-16" );
StringTokenizer perLine = new StringTokenizer( options, "\n" );
String title = perLine.nextToken();
if ( !title.equals( "Font2DTest Option File" ))
throw new Exception( "Not a Font2DTest options file" );
/// Parse all options
boolean displayGridOpt = Boolean.parseBoolean( perLine.nextToken() );
boolean force16ColsOpt = Boolean.parseBoolean( perLine.nextToken() );
boolean showFontInfoOpt = Boolean.parseBoolean( perLine.nextToken() );
String rangeNameOpt = perLine.nextToken();
int rangeStartOpt = Integer.parseInt( perLine.nextToken() );
int rangeEndOpt = Integer.parseInt( perLine.nextToken() );
String fontNameOpt = perLine.nextToken();
float fontSizeOpt = Float.parseFloat( perLine.nextToken() );
int fontStyleOpt = Integer.parseInt( perLine.nextToken() );
int fontTransformOpt = Integer.parseInt( perLine.nextToken() );
int g2TransformOpt = Integer.parseInt( perLine.nextToken() );
int textToUseOpt = Integer.parseInt( perLine.nextToken() );
int drawMethodOpt = Integer.parseInt( perLine.nextToken() );
int antialiasOpt = Integer.parseInt(perLine.nextToken());
int fractionalOpt = Integer.parseInt(perLine.nextToken());
int lcdContrast = Integer.parseInt(perLine.nextToken());
String userTextOpt[] = { "Font2DTest!" };
String dialogEntry = "Font2DTest!";
if (textToUseOpt == fp.USER_TEXT ) {
int numLines = perLine.countTokens(), lineNumber = 0;
if ( numLines != 0 ) {
userTextOpt = new String[ numLines ];
dialogEntry = "";
for ( ; perLine.hasMoreElements(); lineNumber++ ) {
userTextOpt[ lineNumber ] = perLine.nextToken();
dialogEntry += userTextOpt[ lineNumber ] + "\n";
}
}
}
/// Reset GUIs
displayGridCBMI.setState( displayGridOpt );
force16ColsCBMI.setState( force16ColsOpt );
showFontInfoCBMI.setState( showFontInfoOpt );
rm.setSelectedRange( rangeNameOpt, rangeStartOpt, rangeEndOpt );
fontMenu.setSelectedItem( fontNameOpt );
sizeField.setText( String.valueOf( fontSizeOpt ));
styleMenu.setSelectedIndex( fontStyleOpt );
transformMenu.setSelectedIndex( fontTransformOpt );
transformMenuG2.setSelectedIndex( g2TransformOpt );
textMenu.setSelectedIndex( textToUseOpt );
methodsMenu.setSelectedIndex( drawMethodOpt );
antiAliasMenu.setSelectedIndex( antialiasOpt );
fracMetricsMenu.setSelectedIndex( fractionalOpt );
contrastSlider.setValue(lcdContrast);
userTextArea.setText( dialogEntry );
updateGUI();
if ( textToUseOpt == fp.FILE_TEXT ) {
tFileName = perLine.nextToken();
readTextFile(tFileName );
}
/// Reset option variables and repaint
fp.loadOptions( displayGridOpt, force16ColsOpt,
rangeStartOpt, rangeEndOpt,
fontNameOpt, fontSizeOpt,
fontStyleOpt, fontTransformOpt, g2TransformOpt,
textToUseOpt, drawMethodOpt,
antialiasOpt, fractionalOpt,
lcdContrast, userTextOpt );
if ( showFontInfoOpt ) {
fireUpdateFontInfo();
fontInfoDialog.show();
}
else
fontInfoDialog.hide();
}
catch ( Exception ex ) {
fireChangeStatus( "ERROR: Failed to Load Options File; See Stack Trace", true );
ex.printStackTrace();
}
}
public byte[] sendMessageSync(ByteBuffer buffer, int length) throws IOException, ISOClientException {
isoClientEventListener.beforeSendingMessage();
for (byte v :
buffer.array()) {
socketWriter.write(v);
}
socketWriter.flush();
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
socketReader = new BufferedInputStream(socket.getInputStream());
isoClientEventListener.afterSendingMessage();
isoClientEventListener.beforeReceiveResponse();
try {
if(length > 0)
{
byte[] bLen = new byte[length];
socketReader.read(bLen,0,length);
int mLen = (bLen[0] & 0xff) + (bLen[1] & 0xff);
}
int r;
int fo = 512;
do{
r = socketReader.read();
if (!(r == -1 && socketReader.available() == 0)) {
readBuffer.put((byte) r);
} else {
fo--;
}
}while (
((r > -1 && socketReader.available() > 0) ||
(r == -1 && readBuffer.position() <= 1)) &&
fo > 0
);
byte[] resp = Arrays.copyOfRange(readBuffer.array(),0,readBuffer.position());
isoClientEventListener.afterReceiveResponse();
return resp;
} catch (SocketTimeoutException e) {
throw new ISOClientException("Read Timeout");
} finally {
readBuffer.clear();
readBuffer.compact();
readBuffer = null;
}
}
private void exportData(Uri uri) {
try {
ZipOutputStream output = new ZipOutputStream(
new BufferedOutputStream(getContentResolver().openOutputStream(uri))
);
output.putNextEntry(new ZipEntry("backup.json"));
JSONObject json = new JSONObject();
BackupUtils.backup(this, new JSONBackupAgent(json));
output.write(json.toString().getBytes());
output.closeEntry();
File imagesDir = new File(getFilesDir(), "tb_images");
imagesDir.mkdirs();
for(String filename : U.getImageFilenames()) {
File customImage = new File(imagesDir, filename);
if(customImage.exists()) {
output.putNextEntry(new ZipEntry("tb_images/" + filename));
BufferedInputStream input = new BufferedInputStream(new FileInputStream(customImage));
byte[] data = new byte[input.available()];
if(data.length > 0) {
input.read(data);
input.close();
}
output.write(data);
output.closeEntry();
}
}
output.close();
setResult(R.string.tb_backup_successful);
} catch (Throwable e) {
setResult(R.string.tb_backup_failed);
}
}
private void loadOptions( String fileName ) {
try {
BufferedInputStream bis =
new BufferedInputStream( new FileInputStream( fileName ));
int numBytes = bis.available();
byte byteData[] = new byte[ numBytes ];
bis.read( byteData, 0, numBytes );
bis.close();
if ( numBytes < 2 ||
(byteData[0] != (byte) 0xFE || byteData[1] != (byte) 0xFF) )
throw new Exception( "Not a Font2DTest options file" );
String options = new String( byteData, "UTF-16" );
StringTokenizer perLine = new StringTokenizer( options, "\n" );
String title = perLine.nextToken();
if ( !title.equals( "Font2DTest Option File" ))
throw new Exception( "Not a Font2DTest options file" );
/// Parse all options
boolean displayGridOpt = Boolean.parseBoolean( perLine.nextToken() );
boolean force16ColsOpt = Boolean.parseBoolean( perLine.nextToken() );
boolean showFontInfoOpt = Boolean.parseBoolean( perLine.nextToken() );
String rangeNameOpt = perLine.nextToken();
int rangeStartOpt = Integer.parseInt( perLine.nextToken() );
int rangeEndOpt = Integer.parseInt( perLine.nextToken() );
String fontNameOpt = perLine.nextToken();
float fontSizeOpt = Float.parseFloat( perLine.nextToken() );
int fontStyleOpt = Integer.parseInt( perLine.nextToken() );
int fontTransformOpt = Integer.parseInt( perLine.nextToken() );
int g2TransformOpt = Integer.parseInt( perLine.nextToken() );
int textToUseOpt = Integer.parseInt( perLine.nextToken() );
int drawMethodOpt = Integer.parseInt( perLine.nextToken() );
int antialiasOpt = Integer.parseInt(perLine.nextToken());
int fractionalOpt = Integer.parseInt(perLine.nextToken());
int lcdContrast = Integer.parseInt(perLine.nextToken());
String userTextOpt[] = { "Font2DTest!" };
String dialogEntry = "Font2DTest!";
if (textToUseOpt == fp.USER_TEXT ) {
int numLines = perLine.countTokens(), lineNumber = 0;
if ( numLines != 0 ) {
userTextOpt = new String[ numLines ];
dialogEntry = "";
for ( ; perLine.hasMoreElements(); lineNumber++ ) {
userTextOpt[ lineNumber ] = perLine.nextToken();
dialogEntry += userTextOpt[ lineNumber ] + "\n";
}
}
}
/// Reset GUIs
displayGridCBMI.setState( displayGridOpt );
force16ColsCBMI.setState( force16ColsOpt );
showFontInfoCBMI.setState( showFontInfoOpt );
rm.setSelectedRange( rangeNameOpt, rangeStartOpt, rangeEndOpt );
fontMenu.setSelectedItem( fontNameOpt );
sizeField.setText( String.valueOf( fontSizeOpt ));
styleMenu.setSelectedIndex( fontStyleOpt );
transformMenu.setSelectedIndex( fontTransformOpt );
transformMenuG2.setSelectedIndex( g2TransformOpt );
textMenu.setSelectedIndex( textToUseOpt );
methodsMenu.setSelectedIndex( drawMethodOpt );
antiAliasMenu.setSelectedIndex( antialiasOpt );
fracMetricsMenu.setSelectedIndex( fractionalOpt );
contrastSlider.setValue(lcdContrast);
userTextArea.setText( dialogEntry );
updateGUI();
if ( textToUseOpt == fp.FILE_TEXT ) {
tFileName = perLine.nextToken();
readTextFile(tFileName );
}
/// Reset option variables and repaint
fp.loadOptions( displayGridOpt, force16ColsOpt,
rangeStartOpt, rangeEndOpt,
fontNameOpt, fontSizeOpt,
fontStyleOpt, fontTransformOpt, g2TransformOpt,
textToUseOpt, drawMethodOpt,
antialiasOpt, fractionalOpt,
lcdContrast, userTextOpt );
if ( showFontInfoOpt ) {
fireUpdateFontInfo();
fontInfoDialog.show();
}
else
fontInfoDialog.hide();
}
catch ( Exception ex ) {
fireChangeStatus( "ERROR: Failed to Load Options File; See Stack Trace", true );
ex.printStackTrace();
}
}