java.io.InputStream类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(9.6k)|赞(0)|评价(0)|浏览(160)

本文整理了Java中java.io.InputStream类的一些代码示例,展示了InputStream类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。InputStream类的具体详情如下:
包路径:java.io.InputStream
类名称:InputStream

InputStream介绍

[英]A readable source of bytes.

Most clients will use input streams that read data from the file system ( FileInputStream), the network ( java.net.Socket#getInputStream()/ java.net.HttpURLConnection#getInputStream()), or from an in-memory byte array ( ByteArrayInputStream).

Use InputStreamReader to adapt a byte stream like this one into a character stream.

Most clients should wrap their input stream with BufferedInputStream. Callers that do only bulk reads may omit buffering.

Some implementations support marking a position in the input stream and resetting back to this position later. Implementations that don't return false from #markSupported() and throw an IOException when #reset() is called.

Subclassing InputStream

Subclasses that decorate another input stream should consider subclassing FilterInputStream, which delegates all calls to the source input stream.

All input stream subclasses should override both #read() and #read(byte[],int,int). The three argument overload is necessary for bulk access to the data. This is much more efficient than byte-by-byte access.
[中]

代码示例

代码示例来源:origin: stackoverflow.com

public void copy(File src, File dst) throws IOException {
  InputStream in = new FileInputStream(src);
  OutputStream out = new FileOutputStream(dst);

  // Transfer bytes from in to out
  byte[] buf = new byte[1024];
  int len;
  while ((len = in.read(buf)) > 0) {
    out.write(buf, 0, len);
  }
  in.close();
  out.close();
}

代码示例来源:origin: apache/incubator-dubbo

public static void skipUnusedStream(InputStream is) throws IOException {
    if (is.available() > 0) {
      is.skip(is.available());
    }
  }
}

代码示例来源:origin: google/guava

@Override
 public synchronized void reset() throws IOException {
  if (!in.markSupported()) {
   throw new IOException("Mark not supported");
  }
  if (mark == -1) {
   throw new IOException("Mark not set");
  }

  in.reset();
  count = mark;
 }
}

代码示例来源:origin: stackoverflow.com

private String getMmsText(String id) {
  Uri partURI = Uri.parse("content://mms/part/" + id);
  InputStream is = null;
  StringBuilder sb = new StringBuilder();
  try {
    is = getContentResolver().openInputStream(partURI);
    if (is != null) {
      InputStreamReader isr = new InputStreamReader(is, "UTF-8");
      BufferedReader reader = new BufferedReader(isr);
      String temp = reader.readLine();
      while (temp != null) {
        sb.append(temp);
        temp = reader.readLine();
      }
    }
  } catch (IOException e) {}
  finally {
    if (is != null) {
      try {
        is.close();
      } catch (IOException e) {}
    }
  }
  return sb.toString();
}

代码示例来源:origin: stackoverflow.com

HttpURLConnection connection = null;
try {
  URL url = new URL(sUrl[0]);
  connection = (HttpURLConnection) url.openConnection();
  connection.connect();
  if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
    return "Server returned HTTP " + connection.getResponseCode()
        + " " + connection.getResponseMessage();
  int fileLength = connection.getContentLength();
  input = connection.getInputStream();
  output = new FileOutputStream("/sdcard/file_name.extension");
  while ((count = input.read(data)) != -1) {
      input.close();
      return null;
    output.write(data, 0, count);
  try {
    if (output != null)
      output.close();
    if (input != null)
      input.close();
  } catch (IOException ignored) {

代码示例来源:origin: stackoverflow.com

ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
  URL url = new URL(urlToDownload);
  URLConnection connection = url.openConnection();
  connection.connect();
  int fileLength = connection.getContentLength();
  InputStream input = new BufferedInputStream(connection.getInputStream());
  OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk");
  while ((count = input.read(data)) != -1) {
    total += count;
    resultData.putInt("progress" ,(int) (total * 100 / fileLength));
    receiver.send(UPDATE_PROGRESS, resultData);
    output.write(data, 0, count);
  output.flush();
  output.close();
  input.close();
} catch (IOException e) {
  e.printStackTrace();

代码示例来源:origin: googleapis/google-cloud-java

protected final String sendPostRequest(String request) throws IOException {
 URL url = new URL("http", DEFAULT_HOST, this.port, request);
 HttpURLConnection con = (HttpURLConnection) url.openConnection();
 con.setRequestMethod("POST");
 con.setDoOutput(true);
 OutputStream out = con.getOutputStream();
 out.write("".getBytes());
 out.flush();
 InputStream in = con.getInputStream();
 String response = CharStreams.toString(new InputStreamReader(con.getInputStream()));
 in.close();
 return response;
}

代码示例来源:origin: commons-httpclient/commons-httpclient

public void writeRequest(final OutputStream out) throws IOException {
  byte[] tmp = new byte[4096];
  int i = 0;
  InputStream instream = new FileInputStream(this.file);
  try {
    while ((i = instream.read(tmp)) >= 0) {
      out.write(tmp, 0, i);
    }        
  } finally {
    instream.close();
  }
}

代码示例来源:origin: iBotPeaches/Apktool

public void publicizeResources(File arscFile) throws AndrolibException {
  byte[] data = new byte[(int) arscFile.length()];
  try(InputStream in = new FileInputStream(arscFile);
    OutputStream out = new FileOutputStream(arscFile)) {
    in.read(data);
    publicizeResources(data);
    out.write(data);
  } catch (IOException ex){
    throw new AndrolibException(ex);
  }
}

代码示例来源:origin: stackoverflow.com

InputStream in = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// The other side says hello:
String text = br.readLine();
// For whatever reason, you want to read one single byte from the stream,
// That single byte, just after the newline:
byte b = (byte) in.read();

代码示例来源:origin: wildfly/wildfly

public static String readStringFromStdin(String message) throws Exception {
  System.out.print(message);
  System.out.flush();
  System.in.skip(System.in.available());
  BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
  String line=reader.readLine();
  return line != null? line.trim() : null;
}

代码示例来源:origin: libgdx/libgdx

if (extractedFile.exists()) {
  try {
    extractedCrc = crc(new FileInputStream(extractedFile));
  } catch (FileNotFoundException ignored) {
    input = readFile(sourcePath);
    extractedFile.getParentFile().mkdirs();
    output = new FileOutputStream(extractedFile);
    byte[] buffer = new byte[4096];
    while (true) {
      int length = input.read(buffer);
      if (length == -1) break;
      output.write(buffer, 0, length);

代码示例来源:origin: syncany/syncany

/**
 * Downloads the plugin JAR from the given URL to a temporary
 * local location.
 */
private File downloadPluginJar(String pluginJarUrl) throws Exception {
  URL pluginJarFile = new URL(pluginJarUrl);
  logger.log(Level.INFO, "Querying " + pluginJarFile + " ...");
  URLConnection urlConnection = pluginJarFile.openConnection();
  urlConnection.setConnectTimeout(2000);
  urlConnection.setReadTimeout(2000);
  File tempPluginFile = File.createTempFile("syncany-plugin", "tmp");
  tempPluginFile.deleteOnExit();
  logger.log(Level.INFO, "Downloading to " + tempPluginFile + " ...");
  FileOutputStream tempPluginFileOutputStream = new FileOutputStream(tempPluginFile);
  InputStream remoteJarFileInputStream = urlConnection.getInputStream();
  IOUtils.copy(remoteJarFileInputStream, tempPluginFileOutputStream);
  remoteJarFileInputStream.close();
  tempPluginFileOutputStream.close();
  if (!tempPluginFile.exists() || tempPluginFile.length() == 0) {
    throw new Exception("Downloading plugin file failed, URL was " + pluginJarUrl);
  }
  return tempPluginFile;
}

代码示例来源:origin: MorphiaOrg/morphia

private void download(final URL url, final File file) throws IOException {
  LOG.info("Downloading zip data set to " + file);
  InputStream inputStream = url.openStream();
  FileOutputStream outputStream = new FileOutputStream(file);
  try {
    byte[] read = new byte[49152];
    int count;
    while ((count = inputStream.read(read)) != -1) {
      outputStream.write(read, 0, count);
    }
  } finally {
    inputStream.close();
    outputStream.close();
  }
}

代码示例来源:origin: stackoverflow.com

InputStream is = getResources().openRawResource(R.raw.json_file);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
  Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  int n;
  while ((n = reader.read(buffer)) != -1) {
    writer.write(buffer, 0, n);
  }
} finally {
  is.close();
}

String jsonString = writer.toString();

代码示例来源:origin: bumptech/glide

URL url;
try {
 url = new URL(apiUrl);
} catch (MalformedURLException e) {
 throw new RuntimeException(e);
SearchResult result = new SearchResult();
try {
 urlConnection = (HttpURLConnection) url.openConnection();
 is = urlConnection.getInputStream();
 InputStreamReader reader = new InputStreamReader(is);
 result = new Gson().fromJson(reader, SearchResult.class);
} catch (IOException e) {
 if (is != null) {
  try {
   is.close();
  } catch (IOException e) {
  urlConnection.disconnect();

代码示例来源:origin: apache/incubator-dubbo

/**
 * get md5.
 *
 * @param file file source.
 * @return MD5 byte array.
 */
public static byte[] getMD5(File file) throws IOException {
  InputStream is = new FileInputStream(file);
  try {
    return getMD5(is);
  } finally {
    is.close();
  }
}

代码示例来源:origin: stackoverflow.com

Properties properties = new Properties();
InputStream inputStream = new FileInputStream("path/to/file");
try {
  Reader reader = new InputStreamReader(inputStream, "UTF-8");
  try {
    properties.load(reader);
  } finally {
    reader.close();
  }
} finally {
  inputStream.close();
}

代码示例来源:origin: netty/netty

in = url.openStream();
out = new FileOutputStream(tmpFile);
if (TRY_TO_PATCH_SHADED_ID && PlatformDependent.isOsx() && !packagePrefix.isEmpty()) {
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(in.available());
  while ((length = in.read(buffer)) > 0) {
    byteArrayOutputStream.write(buffer, 0, length);
  out.write(bytes);
} else {
  while ((length = in.read(buffer)) > 0) {
    out.write(buffer, 0, length);
out.flush();

代码示例来源:origin: qiurunze123/miaosha

public void run() {
    try {
      for(int i=0;i<10;i++) {
        URL url = new URL("http://192.168.220.130/index.html");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        InputStream in = conn.getInputStream();
        ByteArrayOutputStream bout  = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len = 0;
        while((len = in.read(buff)) >= 0) {
          bout.write(buff, 0, len);
        }
        in.close();
        bout.close();
        byte[] response = bout.toByteArray();
        System.out.println(new String(response, "UTF-8"));
        Thread.sleep(3000);
      }
    }catch(Exception e) {
      
    }
  }
});

相关文章