Java Code Examples for java.io.BufferedInputStream

The following are top voted examples for showing how to use java.io.BufferedInputStream. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: parabuild-ci   File: PseudoServerTest.java   View source code 6 votes vote down vote up
/**
 * This verifies that the PseudoServer can be restricted to a HTTP/1.0.
 */
public void testProtocolThrottling() throws Exception {
    getServer().setMaxProtocolLevel( 1, 0 );
    defineResource( "sample", "Get this", "text/plain" );
    Socket socket = new Socket( "localhost", getHostPort() );
    OutputStream os = socket.getOutputStream();
    InputStream is = new BufferedInputStream( socket.getInputStream() );

    sendHTTPLine( os, "GET /sample HTTP/1.1" );
    sendHTTPLine( os, "Host: meterware.com" );
    sendHTTPLine( os, "Connection: close" );
    sendHTTPLine( os, "" );

    StringBuffer sb = new StringBuffer();
    int b;
    while (-1 != (b = is.read())) sb.append( (char) b );
    String result = sb.toString();
    assertTrue( "Did not find matching protocol", result.startsWith( "HTTP/1.0" ) );
    assertTrue( "Did not find expected text", result.indexOf( "Get this" ) > 0 );
}
 
Example 2
Project: Boulder-Dash   File: Sound.java   View source code 6 votes vote down vote up
/**
 * The sound is load and play in a thread no slow down the engine.
 * */
@Override
public void run() {
    try {
        InputStream in = new BufferedInputStream(this.getClass().getResourceAsStream(this.filename + ".wav"));
        Clip clip = AudioSystem.getClip();

        clip.open(AudioSystem.getAudioInputStream(in));
        if (this.loop){
            clip.loop(Clip.LOOP_CONTINUOUSLY);
        }
        clip.start();
    }catch (Exception e){
        System.err.println(e);
    }

}
 
Example 3
Project: TITAN   File: FtpUtils.java   View source code 6 votes vote down vote up
public boolean uploadFile(File file, byte[] value) {
	boolean result = false;
	if (null == value) {
		return result;
	}
	FTPClient ftpClient = ftpConnManager.getFTPClient();
	if (null == ftpClient || !ftpClient.isConnected()) {
		return result;
	}
	try (BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(value))) {
		boolean storeFile = ftpClient.storeFile(file.getName(), in);
		if (storeFile) {
			result = true;
			log.info("file-->" + file.getPath() + "成功上传至FTP服务器");
		}
	} catch (Exception e) {
		log.error("error", e);
	} finally {
		disconnect(ftpClient);
	}
	return result;
}
 
Example 4
Project: friendlypix-android   File: NewPostUploadTaskFragment.java   View source code 6 votes vote down vote up
public Bitmap decodeSampledBitmapFromUri(Uri fileUri, int reqWidth, int reqHeight)
        throws IOException {
    InputStream stream = new BufferedInputStream(
            mApplicationContext.getContentResolver().openInputStream(fileUri));
    stream.mark(stream.available());
    BitmapFactory.Options options = new BitmapFactory.Options();
    // First decode with inJustDecodeBounds=true to check dimensions
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(stream, null, options);
    stream.reset();
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    BitmapFactory.decodeStream(stream, null, options);
    // Decode bitmap with inSampleSize set
    stream.reset();
    return BitmapFactory.decodeStream(stream, null, options);
}
 
Example 5
Project: Android-Bridge-App   File: Utils.java   View source code 6 votes vote down vote up
/**
 * Load UTF8withBOM or any ansi text file.
 *
 * @throws java.io.IOException
 */
public static String loadFileAsString(String filename) throws java.io.IOException {
    final int BUFLEN = 1024;
    BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN);
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN);
        byte[] bytes = new byte[BUFLEN];
        boolean isUTF8 = false;
        int read, count = 0;
        while ((read = is.read(bytes)) != -1) {
            if (count == 0 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
                isUTF8 = true;
                baos.write(bytes, 3, read - 3); // drop UTF8 bom marker
            } else {
                baos.write(bytes, 0, read);
            }
            count += read;
        }
        return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
    } finally {
        try {
            is.close();
        } catch (Exception ex) {
        }
    }
}
 
Example 6
Project: BaseCore   File: ZipUtils.java   View source code 6 votes vote down vote up
/**
 * 压缩文件
 *
 * @param resFile  需要压缩的文件(夹)
 * @param zipout   压缩的目的文件
 * @param rootpath 压缩的文件路径
 * @throws FileNotFoundException 找不到文件时抛出
 * @throws IOException           当压缩过程出错时抛出
 */
public static void zipFile(File resFile, ZipOutputStream zipout, String rootpath)
        throws FileNotFoundException, IOException {
    rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator)
            + resFile.getName();
    rootpath = new String(rootpath.getBytes("8859_1"), "GB2312");
    if (resFile.isDirectory()) {
        File[] fileList = resFile.listFiles();
        for (File file : fileList) {
            zipFile(file, zipout, rootpath);
        }
    } else {
        byte buffer[] = new byte[BUFF_SIZE];
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile),
                BUFF_SIZE);
        zipout.putNextEntry(new ZipEntry(rootpath));
        int realLength;
        while ((realLength = in.read(buffer)) != -1) {
            zipout.write(buffer, 0, realLength);
        }
        in.close();
        zipout.flush();
        zipout.closeEntry();
    }
}
 
Example 7
Project: VASSAL-src   File: PNGChunkSkipInputStreamTest.java   View source code 6 votes vote down vote up
/**
 * Tests whether iTXt chunks are successfully skipped without losing
 * any other image data.
 */
@Test
public void testSkipiTXt() throws IOException {

  final InputStream ein = new FileInputStream(no_iTXt);
  final byte[] expected = IOUtils.toByteArray(ein);
  ein.close();

  final InputStream rin =
    new PNGChunkSkipInputStream(Collections.singleton(PNGDecoder.iTXt),
    new BufferedInputStream(new FileInputStream(iTXt))
  );
  final byte[] result = IOUtils.toByteArray(rin);
  rin.close();

  assertArrayEquals(expected, result);
}
 
Example 8
Project: openjdk-jdk10   File: DisabledAlgorithms.java   View source code 6 votes vote down vote up
void connect() throws IOException {
    System.out.println("Client: connect to server");
    try (
            BufferedInputStream bis = new BufferedInputStream(
                    socket.getInputStream());
            BufferedOutputStream bos = new BufferedOutputStream(
                    socket.getOutputStream())) {
        bos.write('x');
        bos.flush();

        int read = bis.read();
        if (read < 0) {
            throw new IOException("Client: couldn't read a response");
        }
        socket.getSession().invalidate();
    }
}
 
Example 9
Project: javaide   File: XmlLoader.java   View source code 6 votes vote down vote up
/**
 * Loads an xml file without doing xml validation and return a {@link XmlDocument}
 *
 * @param displayName the xml file display name.
 * @param xmlFile the xml file.
 * @return the initialized {@link XmlDocument}
 */
public static XmlDocument load(
        KeyResolver<String> selectors,
        KeyBasedValueResolver<SystemProperty> systemPropertyResolver,
        String displayName,
        File xmlFile,
        XmlDocument.Type type,
        Optional<String> mainManifestPackageName)
        throws IOException, SAXException, ParserConfigurationException {
    InputStream inputStream = new BufferedInputStream(new FileInputStream(xmlFile));

    PositionXmlParser positionXmlParser = new PositionXmlParser();
    Document domDocument = positionXmlParser.parse(inputStream);
    return domDocument != null
            ? new XmlDocument(positionXmlParser,
            new SourceLocation(displayName, xmlFile),
            selectors,
            systemPropertyResolver,
            domDocument.getDocumentElement(),
            type,
            mainManifestPackageName)
            : null;
}
 
Example 10
Project: osu-beatmap-utils   File: Utils.java   View source code 6 votes vote down vote up
/**
 * Returns the md5 hash of a file in hex form.
 * @param file the file to hash
 * @return the md5 hash
 */
public static String getMD5(File file) {
	try {
		InputStream in = new BufferedInputStream(new FileInputStream(file));
		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] buf = new byte[4096];

		while (true) {
			int len = in.read(buf);
			if (len < 0)
				break;
			md.update(buf, 0, len);
		}
		in.close();

		byte[] md5byte = md.digest();
		StringBuilder result = new StringBuilder();
		for (byte b : md5byte)
			result.append(String.format("%02x", b));
		return result.toString();
	} catch (NoSuchAlgorithmException | IOException e) {
		System.err.println("Failed to calculate MD5 hash.");
	}
	return null;
}
 
Example 11
Project: TSBW4J   File: In.java   View source code 6 votes vote down vote up
/**
 * Initializes an input stream from a URL.
 *
 * @param  url the URL
 * @throws IllegalArgumentException if cannot open {@code url}
 * @throws NullPointerException if {@code url} is {@code null}
 */
public In(URL url) {
    if (url == null) throw new NullPointerException("argument is null");
    try {
        URLConnection site = url.openConnection();
        InputStream is     = site.getInputStream();
        scanner            = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
        scanner.useLocale(LOCALE);
    }
    catch (IOException ioe) {
        throw new IllegalArgumentException("Could not open " + url);
    }
}
 
Example 12
Project: ScrabbleGame   File: GameSaver.java   View source code 6 votes vote down vote up
/**
 * Loads the requested {@link GameSaveInterface} from the requested file
 *
 * @param gameSaveFile The file from which to get the save
 *
 * @return the {@link GameSaveInterface} stored into the given file
 * @throws UnableToLoadSaveException if a problem happens during the loading of the save, for example if the file can't
 *                                   be opened or the content of the file isn't a serialized {@link GameSaveInterface}
 */
public static GameSaveInterface loadGameSave(File gameSaveFile) throws UnableToLoadSaveException {
    // We check the file's integrity, if the save is acceptable.
    if (!gameSaveFile.isFile() || !gameSaveFile.getName().endsWith(GameSaver.GAME_SAVES_FILES_EXTENSION)) {
        throw new UnableToLoadSaveException();
    }

    // We try to load the GameSave from the file. If an error happens, we throw an Exception
    try {
        ObjectInputStream objectInputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(gameSaveFile)));

        GameSaveInterface gameSave = (GameSaveInterface) objectInputStream.readObject();
        objectInputStream.close();

        return gameSave;
    } catch (IOException | ClassNotFoundException e) {
        throw new UnableToLoadSaveException();
    }
}
 
Example 13
Project: hands-on-api-proxy   File: App.java   View source code 6 votes vote down vote up
public SSLContextPinner(String pemAssetName) {
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        InputStream certInputStream = getAssets().open(pemAssetName);
        BufferedInputStream bis = new BufferedInputStream(certInputStream);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        int idx = -1;
        while (bis.available() > 0) {
            Certificate cert = certificateFactory.generateCertificate(bis);
            keyStore.setCertificateEntry("" + ++idx, cert);
            Log.i("App", "pinned " + idx + ": " + ((X509Certificate) cert).getSubjectDN());
        }
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        trustManager = trustManagers[0];
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);
    } catch(Exception e) {
        sslContext = null;
        trustManager = null;
        Log.e("App", e.toString());
    }
}
 
Example 14
Project: myfaces-trinidad   File: URLInputStreamProvider.java   View source code 6 votes vote down vote up
public InputStream openInputStream() throws IOException
{
  // Get the inputstream from the connection to avoid duplicate calls
  // to URL.openConnection
  _lastModifiedTime = URLUtils.getLastModified(_url);
  URLConnection connection = _url.openConnection();

  // avoid URL caching
  // if we use URL caching the files which changed do not get loaded completely
  connection.setUseCaches(false);

  // In theory, should not need to close
  InputStream base = connection.getInputStream();

  if (base instanceof BufferedInputStream)
    return base;
  else
    return new BufferedInputStream(base);
}
 
Example 15
Project: ZooKeeper   File: LearnerHandler.java   View source code 6 votes vote down vote up
LearnerHandler(Socket sock, BufferedInputStream bufferedInput,
               Leader leader) throws IOException {
    super("LearnerHandler-" + sock.getRemoteSocketAddress());
    this.sock = sock;
    this.leader = leader;
    this.bufferedInput = bufferedInput;
    try {
        leader.self.authServer.authenticate(sock,
                new DataInputStream(bufferedInput));
    } catch (IOException e) {
        LOG.error("Server failed to authenticate quorum learner, addr: {}, closing connection",
                sock.getRemoteSocketAddress(), e);
        try {
            sock.close();
        } catch (IOException ie) {
            LOG.error("Exception while closing socket", ie);
        }
        throw new SaslException("Authentication failure: " + e.getMessage());
    }
}
 
Example 16
Project: LoggingInterceptor   File: MainActivity.java   View source code 6 votes vote down vote up
private void downloadFile(ResponseBody body) throws IOException {
    int count;
    byte data[] = new byte[1024 * 4];
    InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
    outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "file.zip");
    OutputStream output = new FileOutputStream(outputFile);
    while ((count = bis.read(data)) != -1) {
        output.write(data, 0, count);
    }

    output.flush();
    output.close();
    bis.close();

    Intent target = new Intent(Intent.ACTION_VIEW);
    target.setDataAndType(Uri.fromFile(outputFile), "application/pdf");
    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

    Intent intent = Intent.createChooser(target, "Open File");
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        e.printStackTrace();
    }
}
 
Example 17
Project: s-store   File: SnapshotUtil.java   View source code 6 votes vote down vote up
/**
 * Check if the CRC of the snapshot file matches the digest.
 * @param f The snapshot file object
 * @return The table list as a string
 * @throws IOException If CRC does not match
 */
public static String CRCCheck(File f) throws IOException {
    final FileInputStream fis = new FileInputStream(f);
    try {
        final BufferedInputStream bis = new BufferedInputStream(fis);
        ByteBuffer crcBuffer = ByteBuffer.allocate(4);
        if (4 != bis.read(crcBuffer.array())) {
            throw new EOFException("EOF while attempting to read CRC from snapshot digest");
        }
        final int crc = crcBuffer.getInt();
        final InputStreamReader isr = new InputStreamReader(bis, "UTF-8");
        CharArrayWriter caw = new CharArrayWriter();
        while (true) {
            int nextChar = isr.read();
            if (nextChar == -1) {
                throw new EOFException("EOF while reading snapshot digest");
            }
            if (nextChar == '\n') {
                break;
            }
            caw.write(nextChar);
        }
        String tableList = caw.toString();
        byte tableListBytes[] = tableList.getBytes("UTF-8");
        CRC32 tableListCRC = new CRC32();
        tableListCRC.update(tableListBytes);
        tableListCRC.update("\n".getBytes("UTF-8"));
        final int calculatedValue = (int)tableListCRC.getValue();
        if (crc != calculatedValue) {
            throw new IOException("CRC of snapshot digest did not match digest contents");
        }

        return tableList;
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (IOException e) {}
    }
}
 
Example 18
Project: Accessibility   File: BitmapUtils.java   View source code 6 votes vote down vote up
public static boolean verifyBitmap(InputStream input) {
    if (input == null) {
        return false;
    }
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    input = input instanceof BufferedInputStream ? input
            : new BufferedInputStream(input);
    BitmapFactory.decodeStream(input, null, options);
    try {
        input.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return (options.outHeight > 0) && (options.outWidth > 0);
}
 
Example 19
Project: EasyAndroid   File: FileTool.java   View source code 6 votes vote down vote up
/**
 * 读取文件file,返回文件内容。如果文件为空,返回空字符串
 *
 * @param file File
 * @return 文件内容
 */
public static String readFile(File file)
{
    try
    {
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        byte[] byteArray = getByteArray();
        StringBuffer stringBuffer = new StringBuffer();
        int length;
        while((length = bis.read(byteArray)) != -1)
        {
            stringBuffer.append(new String(byteArray, 0, length));
        }
        bis.close();
        fis.close();
        return stringBuffer.toString();
    } catch(IOException e)
    {
        e.printStackTrace();
    }

    return TextTool.emptyString();
}
 
Example 20
Project: incubator-netbeans   File: TestUtil.java   View source code 6 votes vote down vote up
public static void unzip( ZipFile zip, File dest ) throws IOException {
    
    for( Enumeration<? extends ZipEntry> e = zip.entries(); e.hasMoreElements(); ) {
        ZipEntry entry = e.nextElement();
        File f = new File( dest, entry.getName() );
        if ( entry.isDirectory() ) {
            f.mkdirs();
        }
        else {
            f.getParentFile().mkdirs();
            f.createNewFile();
            BufferedInputStream bis = new BufferedInputStream( zip.getInputStream( entry ) );            
            BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream( f ) );            
            copyFile( bis, bos );
        }
    }
    
}
 
Example 21
Project: BaseClient   File: CompressedStreamTools.java   View source code 6 votes vote down vote up
/**
 * Load the gzipped compound from the inputstream.
 */
public static NBTTagCompound readCompressed(InputStream is) throws IOException
{
    DataInputStream datainputstream = new DataInputStream(new BufferedInputStream(new GZIPInputStream(is)));
    NBTTagCompound nbttagcompound;

    try
    {
        nbttagcompound = read(datainputstream, NBTSizeTracker.INFINITE);
    }
    finally
    {
        datainputstream.close();
    }

    return nbttagcompound;
}
 
Example 22
Project: incubator-netbeans   File: CheckoutTest.java   View source code 6 votes vote down vote up
private void unpack (String filename) throws IOException {
    File zipLarge = new File(getDataDir(), filename);
    ZipInputStream is = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipLarge)));
    ZipEntry entry;
    while ((entry = is.getNextEntry()) != null) {
        File unpacked = new File(workDir, entry.getName());
        FileChannel channel = new FileOutputStream(unpacked).getChannel();
        byte[] bytes = new byte[2048];
        try {
            int len;
            long size = entry.getSize();
            while (size > 0 && (len = is.read(bytes, 0, 2048)) > 0) {
                ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, len);
                int j = channel.write(buffer);
                size -= len;
            }
        } finally {
            channel.close();
        }
    }
    ZipEntry e = is.getNextEntry();
}
 
Example 23
Project: Lunary-Ethereum-Wallet   File: AddressNameConverter.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public synchronized void load(Context context) throws IOException, ClassNotFoundException {
    FileInputStream fout = new FileInputStream(new File(context.getFilesDir(), "namedb.dat"));
    ObjectInputStream oos = new ObjectInputStream(new BufferedInputStream(fout));
    addressbook = (HashMap<String, String>) oos.readObject();
    oos.close();
    fout.close();
}
 
Example 24
Project: ChronoBike   File: FileSystem.java   View source code 6 votes vote down vote up
public static boolean closeFile(BufferedInputStream bufStreamIn)
{
	try
	{
		if(bufStreamIn != null)
		{
			bufStreamIn.close();
			return true;
		}
	}
	catch (IOException e)
	{
		e.printStackTrace();
	}
	return false;
}
 
Example 25
Project: jdk8u-jdk   File: TestGetSoundbankInputStream.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    File file = new File(System.getProperty("test.src", "."), "ding.dls");
    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);
    try
    {
        Soundbank dls = new DLSSoundbankReader().getSoundbank(bis);
        assertTrue(dls.getInstruments().length == 1);
        Patch patch = dls.getInstruments()[0].getPatch();
        assertTrue(patch.getProgram() == 0);
        assertTrue(patch.getBank() == 0);
    }
    finally
    {
        bis.close();
    }
}
 
Example 26
Project: jaer   File: FordVIVisualizer.java   View source code 6 votes vote down vote up
synchronized public void doLoadFordVIDataFile() {

        JFileChooser c = new JFileChooser(lastFordVIFile);
        FileFilter filt = new FileNameExtensionFilter("Ford Vehicle Interface (VI) data file", "dat");
        c.addChoosableFileFilter(filt);
        c.setFileFilter(filt);
        c.setSelectedFile(new File(lastFordVIFile));
        int ret = c.showOpenDialog(chip.getAeViewer());
        if (ret != JFileChooser.APPROVE_OPTION) {
            return;
        }
        lastFordVIFile = c.getSelectedFile().toString();
        putString("lastFordVIFile", lastFordVIFile);
        try {
            fordViFile = c.getSelectedFile();
            fordViInputStream = new BufferedInputStream(new FileInputStream(fordViFile));
            fordViStates = readFordViJsonStream(fordViInputStream);

        } catch (Exception ex) {
            Logger.getLogger(DavisClassifierCNNProcessor.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(chip.getAeViewer().getFilterFrame(), "Couldn't load from this file, caught exception " + ex + ". See console for logging.", "Bad data file", JOptionPane.WARNING_MESSAGE);
        }

    }
 
Example 27
Project: Clipcon-AndroidClient   File: RetrofitDownloadData.java   View source code 5 votes vote down vote up
/**
 * Download Captured Image Data
 * Change to Image object from file form of Image data
 */
private void downloadCapturedImageData(InputStream inputStream) {
   // inputStream -> bitmap -> file
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    Bitmap imageBitmapData = BitmapFactory.decodeStream(bufferedInputStream);

    imageToGallery(imageBitmapData);
}
 
Example 28
Project: trashjam2017   File: WaveData.java   View source code 5 votes vote down vote up
/**
 * Creates a WaveData container from the specified url
 * 
 * @param path URL to file 
 * @return WaveData containing data, or null if a failure occured
 */
public static WaveData create(URL path) {
	try {
		return create(
			AudioSystem.getAudioInputStream(
				new BufferedInputStream(path.openStream())));
	} catch (Exception e) {
		org.lwjgl.LWJGLUtil.log("Unable to create from: " + path);
		e.printStackTrace();
		return null;
	}		
}
 
Example 29
Project: DAFramework   File: FileController.java   View source code 5 votes vote down vote up
@RequestMapping(value = "/download/{id}")
	public void downloadFile(@PathVariable Long id,HttpServletRequest request, HttpServletResponse response) throws Exception {
		try{
        	if(id != 0){
        		EFile fileInfo = fileDao.fetch(id);
        		if(fileInfo!= null){
        			String path = fileInfo.getPath();
//        			String suffix = path.split("\\.")[1];
					File file = new File(rootPath+path);
//                    String filename = fileInfo.getName()+"."+suffix;
                    InputStream fis = new BufferedInputStream(new FileInputStream(file));
                    byte[] buffer = new byte[fis.available()];
                    fis.read(buffer);
                    fis.close();
                    response.reset();
                    response.addHeader("Content-Disposition","attachment;filename="
                            + new String(java.net.URLEncoder.encode(fileInfo.getName(), "UTF-8")));
                    response.addHeader("Content-Length","" + file.length());
                    response.setContentType("application/octet-stream");
                    OutputStream toClient = new BufferedOutputStream(
                            response.getOutputStream());
                    toClient.write(buffer);
                    toClient.flush();
                    toClient.close();
        		}
        	}
        }catch(Exception e){
			LOG.error("下载失败,原因:"+e.getMessage());
		}
	}
 
Example 30
Project: truevfs   File: TarBZip2Driver.java   View source code 5 votes vote down vote up
@Override
protected InputService<TarDriverEntry> newInput(
        final FsModel model,
        final FsInputSocketSource source)
throws IOException {
    final class Source extends AbstractSource {
        @Override
        public InputStream stream() throws IOException {
            final InputStream in = source.stream();
            try {
                return new BZip2CompressorInputStream(
                        new BufferedInputStream(in, getBufferSize()));
            } catch (final Throwable ex) {
                try {
                    in.close();
                } catch (final Throwable ex2) {
                    ex.addSuppressed(ex2);
                }
                throw ex;
            }
        }
    } // Source
    return new TarInputService(model, new Source(), this);
}
 
Example 31
Project: CS-436_580L_Introduction-to-Machine-Learning   File: Main.java   View source code 5 votes vote down vote up
private static void readHams(String dataSetDirPath, List<Document> dataSet, boolean skipStopwords) {
    File trainingDataSetHamDir = new File(dataSetDirPath + DIR_HAM);
    if (trainingDataSetHamDir.exists() && trainingDataSetHamDir.isDirectory()) {
        File[] hamFiles = trainingDataSetHamDir.listFiles();
        if (hamFiles != null) {
            for (File hamFile : hamFiles) {
                try {
                    Scanner scanner = new Scanner(new BufferedInputStream(new FileInputStream(hamFile)));
                    StringBuilder stringBuilder = new StringBuilder();
                    while (scanner.hasNext()) {
                        stringBuilder.append(scanner.nextLine().toLowerCase());
                    }
                    scanner.close();
                    Document document = new Document();
                    document.setDocumentClass(Document.Class.HAM);
                    String[] split = stringBuilder.toString().split("\\s");
                    List<String> terms = new ArrayList<>();
                    Collections.addAll(terms, split);
                    if (skipStopwords) {
                        terms.removeAll(Stopwords.wordList);
                    }
                    document.setTerms(terms);
                    dataSet.add(document);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
 
Example 32
Project: hadoop   File: BZip2Codec.java   View source code 5 votes vote down vote up
private void internalReset() throws IOException {
  if (needsReset) {
    needsReset = false;
    BufferedInputStream bufferedIn = readStreamHeader();
    input = new CBZip2InputStream(bufferedIn, this.readMode);
  }
}
 
Example 33
Project: Android-Practice   File: DiskLruCache.java   View source code 5 votes vote down vote up
private void readJournal() throws IOException {
    InputStream in = new BufferedInputStream(new FileInputStream(journalFile), IO_BUFFER_SIZE);
    try {
        String magic = readAsciiLine(in);
        String version = readAsciiLine(in);
        String appVersionString = readAsciiLine(in);
        String valueCountString = readAsciiLine(in);
        String blank = readAsciiLine(in);
        if (!MAGIC.equals(magic)
                || !VERSION_1.equals(version)
                || !Integer.toString(appVersion).equals(appVersionString)
                || !Integer.toString(valueCount).equals(valueCountString)
                || !"".equals(blank)) {
            throw new IOException("unexpected journal header: ["
                    + magic + ", " + version + ", " + valueCountString + ", " + blank + "]");
        }

        while (true) {
            try {
                readJournalLine(readAsciiLine(in));
            } catch (EOFException endOfJournal) {
                break;
            }
        }
    } finally {
        closeQuietly(in);
    }
}
 
Example 34
Project: q-mail   File: ParcelFileDescriptorUtil.java   View source code 5 votes vote down vote up
public static <T> DataSinkTransferThread<T> asyncPipeToDataSink(
        SMimeDataSink<T> dataSink, ParcelFileDescriptor output) throws IOException {
    InputStream inputStream = new BufferedInputStream(new AutoCloseInputStream(output));
    DataSinkTransferThread<T> dataSinkTransferThread =
            new DataSinkTransferThread<T>(dataSink, inputStream);
    dataSinkTransferThread.start();
    return dataSinkTransferThread;
}
 
Example 35
Project: mi-firma-android   File: AOUtil.java   View source code 5 votes vote down vote up
/** Obtiene el flujo de entrada de un fichero (para su lectura) a partir de su URI.
 * @param uri URI del fichero a leer
 * @return Flujo de entrada hacia el contenido del fichero
 * @throws IOException Cuando no se ha podido abrir el fichero de datos. */
public static InputStream loadFile(final URI uri) throws IOException {

    if (uri == null) {
        throw new IllegalArgumentException("Se ha pedido el contenido de una URI nula"); //$NON-NLS-1$
    }

    if (uri.getScheme().equals("file")) { //$NON-NLS-1$
        // Es un fichero en disco. Las URL de Java no soportan file://, con
        // lo que hay que diferenciarlo a mano

        // Retiramos el "file://" de la uri
        String path = uri.getSchemeSpecificPart();
        if (path.startsWith("//")) { //$NON-NLS-1$
            path = path.substring(2);
        }
        return new FileInputStream(new File(path));
    }

    // Es una URL
    final InputStream tmpStream = new BufferedInputStream(uri.toURL().openStream());

    // Las firmas via URL fallan en la descarga por temas de Sun, asi que
    // descargamos primero
    // y devolvemos un Stream contra un array de bytes
    final byte[] tmpBuffer = getDataFromInputStream(tmpStream);

    return new java.io.ByteArrayInputStream(tmpBuffer);
}
 
Example 36
Project: RootPGPExplorer   File: MyPGPUtil.java   View source code 5 votes vote down vote up
public static PGPPublicKey readPublicKey(String fileName) throws IOException, PGPException
{
    InputStream keyIn   = new BufferedInputStream(new FileInputStream(fileName));
    PGPPublicKey pubKey = readPublicKey(keyIn);
    keyIn.close();
    return pubKey;
}
 
Example 37
Project: nc-android-webrtcpeer   File: DefaultSocketService.java   View source code 5 votes vote down vote up
public void setTrustedCertificate(InputStream inputFile) {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = new BufferedInputStream(inputFile);
        Certificate ca = cf.generateCertificate(caInput);

        // Create a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 38
Project: LCL   File: GameMusic.java   View source code 5 votes vote down vote up
public void play() {
    try {
        BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(filename));
        player = new Player(buffer);
        player.play();
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 39
Project: fdk-java   File: ReadOnceInputEvent.java   View source code 5 votes vote down vote up
public ReadOnceInputEvent(String appName, String route, String requestUrl, String method, InputStream body, Headers headers, QueryParameters parameters) {
    this.appName = Objects.requireNonNull(appName);
    this.route = Objects.requireNonNull(route);
    this.requestUrl = Objects.requireNonNull(requestUrl);
    this.method = Objects.requireNonNull(method).toUpperCase();
    this.body = new BufferedInputStream(Objects.requireNonNull(body));
    this.headers = Objects.requireNonNull(headers);
    this.queryParameters = Objects.requireNonNull(parameters);
    body.mark(Integer.MAX_VALUE);
}
 
Example 40
Project: rasa-botmill-plugin   File: NetworkUtils.java   View source code 5 votes vote down vote up
/**
 * Utility method that converts an HttpResponse to a String.
 *
 * @param response
 *            the response to convert.
 * @return a String with the response content.
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private static String getResponseContent(HttpResponse response) throws IOException {
	InputStream inputStream = response.getEntity().getContent();
	BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
	InputStreamReader inputStreamReader = new InputStreamReader(bufferedInputStream);
	BufferedReader br = new BufferedReader(inputStreamReader);
	StringBuilder builder = new StringBuilder();
	String output = null;
	while ((output = br.readLine()) != null) {
		builder.append(output);
	}
	return builder.toString();
}