java.io.BufferedInputStream#read ( )源码实例Demo

下面列出了java.io.BufferedInputStream#read ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: kardio   文件: MailSenderUtil.java
/**
 * Send message to Webhook URL
 * 
 * @param subscription
 * @throws IOException
 */
public void sentMessageToWebhook(String webhookUrl, String message) throws IOException {
    
    Log.debug("Webhook Message : " + message);
    URL myurl = new URL(webhookUrl);
    HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
    con.setRequestMethod("POST");

    con.setRequestProperty("Content-length", String.valueOf(message.length()));
    con.setRequestProperty("Content-Type", "application/json");
    con.setDoOutput(true);
    con.setDoInput(true);

    DataOutputStream output = new DataOutputStream(con.getOutputStream());
    output.writeBytes(message);
    output.flush();
    output.close();

    BufferedInputStream inStream = new BufferedInputStream(con.getInputStream());
    byte[] b = new byte[256];
    inStream.read(b);
    Log.debug("Response : " + new String(b));
}
 
/**
 * Copies the data in an input stream to a target file if the magic number matches.
 *
 * If the magic number does not match the expected value, this method throws an
 * IOException. Other usual conditions for IOException or FileNotFoundException
 * also apply.
 *
 * @param input the stream to be copied.
 * @param output an output stream to copy the data to.
 */
public static void checkMagicAndCopyFileTo(final BufferedInputStream input,
        final BufferedOutputStream output) throws FileNotFoundException, IOException {
    // Check the magic number
    final int length = MAGIC_NUMBER_VERSION_2.length;
    final byte[] magicNumberBuffer = new byte[length];
    final int readMagicNumberSize = input.read(magicNumberBuffer, 0, length);
    if (readMagicNumberSize < length) {
        throw new IOException("Less bytes to read than the magic number length");
    }
    if (SHOULD_VERIFY_MAGIC_NUMBER) {
        if (!Arrays.equals(MAGIC_NUMBER_VERSION_2, magicNumberBuffer)) {
            if (!Arrays.equals(MAGIC_NUMBER_VERSION_1, magicNumberBuffer)) {
                throw new IOException("Wrong magic number for downloaded file");
            }
        }
    }
    output.write(magicNumberBuffer);

    // Actually copy the file
    final byte[] buffer = new byte[FILE_READ_BUFFER_SIZE];
    for (int readBytes = input.read(buffer); readBytes >= 0; readBytes = input.read(buffer)) {
        output.write(buffer, 0, readBytes);
    }
    input.close();
}
 
源代码3 项目: openboard   文件: BinaryDictionaryFileDumper.java
/**
 * Copies the data in an input stream to a target file if the magic number matches.
 *
 * If the magic number does not match the expected value, this method throws an
 * IOException. Other usual conditions for IOException or FileNotFoundException
 * also apply.
 *
 * @param input the stream to be copied.
 * @param output an output stream to copy the data to.
 */
public static void checkMagicAndCopyFileTo(final BufferedInputStream input,
        final BufferedOutputStream output) throws IOException {
    // Check the magic number
    final int length = MAGIC_NUMBER_VERSION_2.length;
    final byte[] magicNumberBuffer = new byte[length];
    final int readMagicNumberSize = input.read(magicNumberBuffer, 0, length);
    if (readMagicNumberSize < length) {
        throw new IOException("Less bytes to read than the magic number length");
    }
    if (SHOULD_VERIFY_MAGIC_NUMBER) {
        if (!Arrays.equals(MAGIC_NUMBER_VERSION_2, magicNumberBuffer)) {
            if (!Arrays.equals(MAGIC_NUMBER_VERSION_1, magicNumberBuffer)) {
                throw new IOException("Wrong magic number for downloaded file");
            }
        }
    }
    output.write(magicNumberBuffer);

    // Actually copy the file
    final byte[] buffer = new byte[FILE_READ_BUFFER_SIZE];
    for (int readBytes = input.read(buffer); readBytes >= 0; readBytes = input.read(buffer)) {
        output.write(buffer, 0, readBytes);
    }
    input.close();
}
 
源代码4 项目: UploadFile   文件: UploadFileServlet.java
public static void inputStream2File(InputStream is, String savePath)
		throws Exception
{
	System.out.println("�ļ�����·��Ϊ:" + savePath);
	File file = new File(savePath);
	InputStream inputSteam = is;
	BufferedInputStream fis = new BufferedInputStream(inputSteam);
	FileOutputStream fos = new FileOutputStream(file);
	int f;
	while ((f = fis.read()) != -1)
	{
		fos.write(f);
	}
	fos.flush();
	fos.close();
	fis.close();
	inputSteam.close();
	
}
 
源代码5 项目: nebula   文件: SvgLoader.java
static SvgDocument load(InputStream in) {
	StringBuilder sb = new StringBuilder();
	BufferedInputStream bis = new BufferedInputStream(in);
	int i;
	try {
		while((i = bis.read()) != -1) {
			char c = (char) i;
			if(Character.isWhitespace(c)) { // replace all whitespace chars with a space char
				if(' ' != sb.charAt(sb.length() - 1)) { // no point in having multiple spaces
					sb.append(' ');
				}
			} else {
				sb.append(c);
			}
		}
	} catch(IOException e) {
		e.printStackTrace();
	}
	char[] ca = new char[sb.length()];
	sb.getChars(0, sb.length(), ca, 0);
	SvgDocument doc = new SvgDocument();
	parse(doc, ca, 0, ca.length - 1);
	return doc;
}
 
源代码6 项目: Lottery   文件: DataAct.java
private  String readFile(String filename) throws IOException {
    File file =new File(filename);
    if(filename==null || filename.equals(""))
    {
      throw new NullPointerException("<@s.m 'db.fileerror'/>");
    }
    long len = file.length();
    byte[] bytes = new byte[(int)len];
    BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(file));
    int r = bufferedInputStream.read( bytes );
    if (r != len)
      throw new IOException("<@s.m 'db.filereaderror'/>");
    bufferedInputStream.close();
    return new String(bytes,"utf-8");
}
 
源代码7 项目: openjdk-jdk8u   文件: OctaneTest.java
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;
        }
    }
 
源代码8 项目: birt   文件: TestPPTX2PNG.java
private void copyResource( String resource, String fileName )
		throws IOException
{
	InputStream in = DesignToPNG.class.getClassLoader( )
			.getResourceAsStream( resource );
	if ( in == null )
	{
		throw new IOException( );
	}
	new File( fileName ).getParentFile( ).mkdirs( );
	BufferedInputStream bi = new BufferedInputStream( in );
	FileOutputStream fi = new FileOutputStream( fileName );
	try
	{
		byte[] buffer = new byte[4096];
		int size = bi.read( buffer );
		while ( size > 0 )
		{
			fi.write( buffer, 0, size );
			size = bi.read( buffer );
		}
	}
	finally
	{
		fi.close( );
		bi.close( );
		in.close( );
	}

}
 
源代码9 项目: gemfirexd-oss   文件: SimpleDiff.java
public void pause()
{
    BufferedInputStream bis = new BufferedInputStream(System.in);
    try
    {
        bis.read();
    }
    catch (IOException ioe)
    {
        pw.println("Error trying to pause...");
        System.out.println("Error trying to pause...");
    }
}
 
源代码10 项目: org.alloytools.alloy   文件: SimAtom.java
/**
 * Read a "..." atom assuming the leading " has already been consumed.
 */
static SimAtom read(BufferedInputStream in) throws IOException {
    byte temp[] = new byte[64]; // to ensure proper detection of
                               // out-of-memory error, this number must be
                               // 2^n for some n>=0
    int n = 0;
    while (true) {
        int c = in.read();
        if (c < 0)
            throw new IOException("Unexpected EOF");
        if (c == '\"')
            break;
        if (c == '\\') {
            c = in.read();
            if (c < 0)
                throw new IOException("Unexpected EOF");
            if (c == 'n')
                c = '\n';
        }
        while (n >= temp.length) {
            byte temp2[] = new byte[temp.length * 2];
            System.arraycopy(temp, 0, temp2, 0, temp.length);
            temp = temp2;
        }
        temp[n] = (byte) c;
        n++;
    }
    return make(new String(temp, 0, n, "UTF-8"));
}
 
源代码11 项目: Evolve   文件: Utils.java
@Override
protected Boolean doInBackground(String... vals) {
    try{
        URL updateURL = new URL(vals[0]);
        URLConnection conn = updateURL.openConnection();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);

        int current = 0;
        while((current = bis.read()) != -1){
            baf.append((byte)current);
        }

     /* Convert the Bytes read to a String. */
        final String s = new String(baf.toByteArray());

     /* Get current Version Number */
        int curVersion = Integer.valueOf(vals[1]);
        int newVersion = Integer.valueOf(s);

     /* Is a higher version than the current already out? */
        if (newVersion > curVersion) {
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
源代码12 项目: dawnsci   文件: FileUtils.java
/**
 * @param source
 * @param destination_file
 * @throws IOException
 */
public final static void write(final BufferedInputStream source, final File destination_file) throws IOException {

	final File parTo = destination_file.getParentFile();
	if (!parTo.exists()) {
		parTo.mkdirs();
	}
	if (!destination_file.exists()) {
		destination_file.createNewFile();
	}

	OutputStream destination = null;
	try {

		destination = new BufferedOutputStream(new FileOutputStream(destination_file));
		byte[] buffer = new byte[FileUtils.getBufferSize()];
		int bytes_read;

		while (true) {
			bytes_read = source.read(buffer);
			if (bytes_read == -1) {
				break;
			}
			destination.write(buffer, 0, bytes_read);
		}

	} finally {
		source.close();
		if (destination != null) {
			destination.close();
		}
	}
}
 
源代码13 项目: Ency   文件: ImagePresenter.java
private void saveToDisk(File imageFile, ResponseBody body) throws IOException {
    InputStream is = body.byteStream();
    FileOutputStream fos = new FileOutputStream(imageFile);
    BufferedInputStream bis = new BufferedInputStream(is);
    byte[] buffer = new byte[1024];
    int len;
    while ((len = bis.read(buffer)) != -1) {
        fos.write(buffer, 0, len);
    }
    fos.flush();
    fos.close();
    bis.close();
    is.close();
}
 
源代码14 项目: Flashtool   文件: URLDownloader.java
public long Download(String strurl, String filedest, long seek) throws IOException {
	try {
		// Setup connection.
        URL url = new URL(strurl);
        URLConnection connection = url.openConnection();
        
        File fdest = new File(filedest);
        connection.connect();
        mDownloaded = 0;
        mFileLength = connection.getContentLength();
        strLastModified = connection.getHeaderField("Last-Modified");
        Map<String, List<String>> map = connection.getHeaderFields();

        // Setup streams and buffers.
        int chunk = 131072;
        input = new BufferedInputStream(connection.getInputStream(), chunk);
        outFile = new RandomAccessFile(fdest, "rw");
        outFile.seek(seek);
        
        byte data[] = new byte[chunk];
        LogProgress.initProgress(100);
        long i=0;
        // Download file.
        for (int count=0; (count=input.read(data, 0, chunk)) != -1; i++) { 
            outFile.write(data, 0, count);
            mDownloaded += count;
            
            LogProgress.updateProgressValue((int) (mDownloaded * 100 / mFileLength));
            if (mDownloaded >= mFileLength)
                break;
            if (canceled) break;
        }
        // Close streams.
        outFile.close();
        input.close();
        return mDownloaded;
	}
	catch (IOException ioe) {
		try {
			outFile.close();
		} catch (Exception ex1) {}
		try {
			input.close();
		} catch (Exception ex2) {}
		if (canceled) throw new IOException("Job canceled");
		throw ioe;
	}
}
 
源代码15 项目: birt   文件: BaseTestCase.java
/**
 * Parses an input file as the design values instance.
 * 
 * @param fileName
 * @return
 * @throws IOException
 * 
 * 
 */

protected DesignValues readDesignValuesFromFile( String fileName )
		throws IOException
{
	fileName = INPUT_FOLDER + fileName;

	InputStream is = getResource( fileName ).openStream( );

	BufferedInputStream baIs = new BufferedInputStream( is );

	byte[] b = new byte[8192];
	baIs.read( b );

	String strDesignValues = new String( b, "utf-8" );

	DesignValues tmpValues = SerializerImpl.instance( ).read( strDesignValues );

	baIs.close( );
	is.close( );

	return tmpValues;
}
 
源代码16 项目: BigDataScript   文件: TailFileMulti.java
/**
 * Check if there is output available on any file
 * @returns Number of bytes read. Negative number of there were problems
 */
@Override
protected int tail() {
	if (!exists) {
		exists = inputFile.exists();
		if (!exists) return 0;
	}

	// File size
	long size = inputFile.length();
	if (size <= inputPos) return 0;

	int avail = (int) (size - inputPos);
	int count = 0;
	try {
		// Open input
		FileInputStream fis = new FileInputStream(inputFileName);
		fis.skip(inputPos);
		BufferedInputStream input = new BufferedInputStream(fis);

		BufferedOutputStream output = null;
		avail = input.available();

		while (avail > 0) {
			// Read all available bytes
			avail = Math.min(avail, MAX_BUFFER_SIZE); // Limit buffer size (some systems return MAX_INT when the file is growing)
			byte[] bytes = new byte[avail];
			count = input.read(bytes);
			inputPos += count;

			// Show bytes
			if (showStderr) System.err.write(bytes, 0, count);
			else System.out.write(bytes, 0, count);

			// Write to output
			if (output != null) output.write(bytes, 0, count);

			avail = input.available(); // Something more to read?
		}

		// Close input and output
		input.close();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	return count;
}
 
源代码17 项目: jwala   文件: JschServiceImpl.java
/**
 * Reads data streamed from a remote connection
 *
 * @param remoteOutput  the inputstream where the remote connection will stream data to
 * @param dataEndMarker a marker which tells the method to stop reading from the inputstream. If this is null
 *                      then the method will try to read data from the input stream until read timeout is reached.
 * @param timeout       the length of time in which to wait for incoming data from the stream
 * @return the data streamed from the remote connection
 * @throws IOException thrown when reading bytes from input stream
 */
private String readRemoteOutput(final InputStream remoteOutput, final Character dataEndMarker, final long timeout)
        throws IOException {

    if (null == dataEndMarker) {
        throw new JschServiceException("Expecting non-null end marker when reading remote output");
    }

    final int readInputSleepDuration = Integer.parseInt(ApplicationProperties.get(
            JSCH_CHANNEL_SHELL_READ_INPUT_SLEEP_DURATION.getPropertyName(), SHELL_READ_SLEEP_DEFAULT_VALUE));
    final BufferedInputStream buffIn = new BufferedInputStream(remoteOutput);
    final byte[] bytes = new byte[BYTE_CHUNK_SIZE];
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    String result;
    LOGGER.debug("Default char encoding:" + Charset.defaultCharset());
    long startTime = System.currentTimeMillis();
    try {
        while (true) {
            if (buffIn.available() != 0) {
                final int size = buffIn.read(bytes);

                if (size > 0) {
                    LOGGER.debug("Read:" + size + " bytes");
                    out.write(bytes, 0, size);
                    LOGGER.debug("Bytes read as String: " + new String(bytes));
                }

                startTime = System.currentTimeMillis();

                // Alternative method of checking if we got our 'EOF' character.
                boolean stopReading = false;
                for(int b=0;b<size;b++) {
                    if (bytes[b]==-1) {
                        LOGGER.debug("Read EOF byte '{}', stopping remote output reading...", bytes[size - 1]);
                        stopReading=true;
                    }
                }

                if (stopReading) {
                    break;
                }

                // need to verify this works on non-windows systems
                // currently setting the encoding to UTF8, UTF16, ASCII, or ISO all fail this conditional
                // e.g. new String(bytes, StandardCharsets.UTF-8)
                // printing out Charset.defaultCharset() shows it's using windows-1252 on a Windows JVM
                if (new String(bytes).indexOf(dataEndMarker) > -1) {
                    LOGGER.debug("Read EOF character '{}', stopping remote output reading...", bytes[size - 1]);
                    break;
                }
            }

            if ((System.currentTimeMillis() - startTime) > timeout) {
                LOGGER.warn("Remote output reading timeout!");
                break;
            }

            try {
                Thread.sleep(readInputSleepDuration);
            } catch (final InterruptedException e) {
                final String errMsg =  "readRemoteOutput was interrupted while waiting for input from JSch channel!";
                LOGGER.error(errMsg, e);
                throw new JschServiceException(errMsg, e);
            }
        }
    } finally {
        result = out.toString(StandardCharsets.UTF_8.name());
        out.close();
    }

    return result;
}
 
源代码18 项目: seleniumtestsframework   文件: FileUtility.java
public static void extractJar(final String storeLocation, final Class<?> clz) throws IOException {
    File firefoxProfile = new File(storeLocation);
    String location = clz.getProtectionDomain().getCodeSource().getLocation().getFile();

    JarFile jar = new JarFile(location);
    System.out.println("Extracting jar file::: " + location);
    firefoxProfile.mkdir();

    Enumeration<?> jarFiles = jar.entries();
    while (jarFiles.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) jarFiles.nextElement();
        String currentEntry = entry.getName();
        File destinationFile = new File(storeLocation, currentEntry);
        File destinationParent = destinationFile.getParentFile();

        // create the parent directory structure if required
        destinationParent.mkdirs();
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(jar.getInputStream(entry));
            int currentByte;

            // buffer for writing file
            byte[] data = new byte[BUFFER];

            // write the current file to disk
            FileOutputStream fos = new FileOutputStream(destinationFile);
            BufferedOutputStream destination = new BufferedOutputStream(fos, BUFFER);

            // read and write till last byte
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                destination.write(data, 0, currentByte);
            }

            destination.flush();
            destination.close();
            is.close();
        }
    }

    FileUtils.deleteDirectory(new File(storeLocation + "\\META-INF"));
    if (OSUtility.isWindows()) {
        new File(storeLocation + "\\" + clz.getCanonicalName().replaceAll("\\.", "\\\\") + ".class").delete();
    } else {
        new File(storeLocation + "/" + clz.getCanonicalName().replaceAll("\\.", "/") + ".class").delete();
    }
}
 
源代码19 项目: android-advanced-decode   文件: FileManager.java
public static byte[] readRawBytes(File source) {
	try {
		if (Log.isLoggable("InstantRun", 2)) {
			Log.v("InstantRun", "Reading the bytes for file " + source);
		}
		long length = source.length();
		if (length > 2147483647L) {
			if (Log.isLoggable("InstantRun", 2)) {
				Log.v("InstantRun", "File too large (" + length + ")");
			}
			return null;
		}
		byte[] result = new byte[(int) length];

		BufferedInputStream input = new BufferedInputStream(
				new FileInputStream(source));
		try {
			int index = 0;
			int remaining = result.length - index;
			int numRead;
			while (remaining > 0) {
				numRead = input.read(result, index, remaining);
				if (numRead == -1) {
					break;
				}
				index += numRead;
				remaining -= numRead;
			}
			if (Log.isLoggable("InstantRun", 2)) {
				Log.v("InstantRun", "Returning length " + result.length
						+ " for file " + source);
			}
			return result;
		} finally {
			input.close();
		}
	} catch (IOException ioe) {
		if (Log.isLoggable("InstantRun", 6)) {
			Log.e("InstantRun", "Failed to read file " + source, ioe);
		}
		if (Log.isLoggable("InstantRun", 2)) {
			Log.v("InstantRun", "I/O error, no bytes returned for "
					+ source);
		}
	}
	return null;
}
 
源代码20 项目: ET_Redux   文件: MathMachineII.java
/**
 *
 * @param variables
 * @param rootDirectoryName
 * @param createNewExpressionFilesXML
 * @throws IOException
 */
public static void outputExpressionFilesXML(//
        ValueModel[][] variables,
        String rootDirectoryName,
        boolean createNewExpressionFilesXML) throws IOException {

    // drive ExpTreeII output from here

    if (createNewExpressionFilesXML) {
        MathMachineII.expFiles = new HashMap<>();
        MathMachineII.rootDirectoryName = rootDirectoryName;
    }

    File rootDirectory = new File("." + File.separator + rootDirectoryName+File.separator);


    if (rootDirectory.exists()) {
        if (createNewExpressionFilesXML) {
            // find and delete all .xml files
            File[] expressionFilesXML = rootDirectory.listFiles(new FractionXMLFileFilter());
            for (File f : expressionFilesXML) {
                f.delete();
            }
        }
    } else {
        rootDirectory.mkdir();
    }

    FileOutputStream outputDirectoryDest = new FileOutputStream(rootDirectory+".zip");
    ZipOutputStream output = new ZipOutputStream(outputDirectoryDest);
    int BUFFER = 2048;
    byte[] data = new byte[BUFFER];
    

    for (ValueModel[] vms : variables) {
        for (ValueModel valueModel : vms) {
            FileInputStream input = new FileInputStream("."
                    + File.separator
                    + rootDirectoryName
                    + File.separator
                    + createPresentationFileVMs(valueModel.getValueTree(), valueModel.differenceValueCalcs()));
            ZipEntry entry = new ZipEntry(valueModel.getName());
            output.putNextEntry(entry);
            BufferedInputStream in = new BufferedInputStream(input, BUFFER);
            int count;
            while ((count = in.read(data, 0, BUFFER)) != -1) {
                output.write(data, 0, count);
            }
            output.closeEntry();
            in.close();
        }
    }
    output.close();
}