Tabnine Logo
InputStreamReader
Code IndexAdd Tabnine to your IDE (free)

How to use
InputStreamReader
in
java.io

Best Java code snippets using java.io.InputStreamReader (Showing top 20 results out of 110,178)

Refine searchRefine arrow

  • BufferedReader
  • URL
  • FileInputStream
  • URLConnection
  • InputStream
  • HttpURLConnection
  • HttpResponse
canonical example by Tabnine

public void postRequest(String urlStr, String jsonBodyStr) throws IOException {
  URL url = new URL(urlStr);
  HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
  httpURLConnection.setDoOutput(true);
  httpURLConnection.setRequestMethod("POST");
  httpURLConnection.setRequestProperty("Content-Type", "application/json");
  try (OutputStream outputStream = httpURLConnection.getOutputStream()) { 
   outputStream.write(jsonBodyStr.getBytes());
   outputStream.flush();
  }
  if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()))) {
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        // ... do something with line
      }
    }
  } else {
    // ... do something with unsuccessful response
  }
}
canonical example by Tabnine

public void readAllLines(InputStream in) throws IOException {
 try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in))) {
  String line;
  while ((line = bufferedReader.readLine()) != null) {
   // ... do something with line
  }
 }
}
origin: stackoverflow.com

 HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);
origin: stanfordnlp/CoreNLP

public TraditionalSimplifiedCharacterMap(String path) {
 // TODO: gzipped maps might be faster
 try {
  FileInputStream fis = new FileInputStream(path);
  InputStreamReader isr = new InputStreamReader(fis, "utf-8");
  BufferedReader br = new BufferedReader(isr);
  init(br);
  br.close();
  isr.close();
  fis.close();
 } catch (IOException e) {
  throw new RuntimeIOException(e);
 }
}
origin: libgdx/libgdx

/** Copy the data from an {@link InputStream} to a string using the specified charset.
 * @param estimatedSize Used to allocate the output buffer to possibly avoid an array copy.
 * @param charset May be null to use the platform's default charset. */
public static String copyStreamToString (InputStream input, int estimatedSize, String charset) throws IOException {
  InputStreamReader reader = charset == null ? new InputStreamReader(input) : new InputStreamReader(input, charset);
  StringWriter writer = new StringWriter(Math.max(0, estimatedSize));
  char[] buffer = new char[DEFAULT_BUFFER_SIZE];
  int charsRead;
  while ((charsRead = reader.read(buffer)) != -1) {
    writer.write(buffer, 0, charsRead);
  }
  return writer.toString();
}
origin: alibaba/jstorm

static Map loadYamlConf(String f) throws IOException {
  InputStreamReader reader = null;
  try {
    FileInputStream fis = new FileInputStream(f);
    reader = new InputStreamReader(fis, UTF8);
    return (Map) yaml.load(reader);
  } finally {
    if (reader != null)
      reader.close();
  }
}
origin: apache/storm

public static Map<String, Object> fromCompressedJsonConf(byte[] serialized) {
  try {
    ByteArrayInputStream bis = new ByteArrayInputStream(serialized);
    InputStreamReader in = new InputStreamReader(new GZIPInputStream(bis));
    Object ret = JSONValue.parseWithException(in);
    in.close();
    return (Map<String, Object>) ret;
  } catch (IOException | ParseException e) {
    throw new RuntimeException(e);
  }
}
origin: stackoverflow.com

 import java.net.*;
import java.io.*;

public class URLConnectionReader {
  public static void main(String[] args) throws Exception {
    URL yahoo = new URL("http://www.yahoo.com/");
    URLConnection yc = yahoo.openConnection();
    BufferedReader in = new BufferedReader(
                new InputStreamReader(
                yc.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null) 
      System.out.println(inputLine);
    in.close();
  }
}
origin: google/guava

/**
 * Returns a buffered reader that reads from a file using the given character set.
 *
 * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
 * java.nio.file.Files#newBufferedReader(java.nio.file.Path, Charset)}.
 *
 * @param file the file to read from
 * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
 *     helpful predefined constants
 * @return the buffered reader
 */
public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException {
 checkNotNull(file);
 checkNotNull(charset);
 return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
}
origin: stackoverflow.com

 String line;
try (
  InputStream fis = new FileInputStream("the_file_name");
  InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
  BufferedReader br = new BufferedReader(isr);
) {
  while ((line = br.readLine()) != null) {
    // Deal with the line
  }
}
origin: stackoverflow.com

 import java.net.*;
import java.io.*;

URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
        whatismyip.openStream()));

String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);
origin: airbnb/lottie-android

@WorkerThread
private LottieResult fetchFromNetworkInternal() throws IOException {
 L.debug( "Fetching " + url);
 HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
 connection.setRequestMethod("GET");
 connection.connect();
 if (connection.getErrorStream() != null || connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
  BufferedReader r = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
  StringBuilder error = new StringBuilder();
  String line;
  while ((line = r.readLine()) != null) {
   error.append(line).append('\n');
   extension = FileExtension.Zip;
   file = networkCache.writeTempCacheFile(connection.getInputStream(), extension);
   result = LottieCompositionFactory.fromZipStreamSync(new ZipInputStream(new FileInputStream(file)), url);
   break;
  case "application/json":
   extension = FileExtension.Json;
   file = networkCache.writeTempCacheFile(connection.getInputStream(), extension);
   result = LottieCompositionFactory.fromJsonInputStreamSync(new FileInputStream(new File(file.getAbsolutePath())), url);
   break;
origin: stackoverflow.com

 String urlParameters = "param1=a&param2=b&param3=c";
URL url = new URL("http://example.com/index.php");
URLConnection conn = url.openConnection();

conn.setDoOutput(true);

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

writer.write(urlParameters);
writer.flush();

String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((line = reader.readLine()) != null) {
  System.out.println(line);
}
writer.close();
reader.close();
origin: stackoverflow.com

 URL url = new URL(targetURL);
 connection = (HttpURLConnection) url.openConnection();
 connection.setRequestMethod("POST");
 connection.setRequestProperty("Content-Type", 
   "application/x-www-form-urlencoded");
 connection.setRequestProperty("Content-Length", 
   Integer.toString(urlParameters.getBytes().length));
 connection.setRequestProperty("Content-Language", "en-US");  
 connection.setUseCaches(false);
 InputStream is = connection.getInputStream();
 BufferedReader rd = new BufferedReader(new InputStreamReader(is));
 StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
 String line;
 while ((line = rd.readLine()) != null) {
  response.append(line);
  response.append('\r');
 rd.close();
 return response.toString();
} catch (Exception e) {
} finally {
 if (connection != null) {
  connection.disconnect();
origin: apache/incubator-pinot

private boolean updateIndexConfig(String tableName, TableConfig tableConfig)
  throws Exception {
 String request =
   ControllerRequestURLBuilder.baseUrl("http://" + _controllerAddress).forTableUpdateIndexingConfigs(tableName);
 HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(request).openConnection();
 httpURLConnection.setDoOutput(true);
 httpURLConnection.setRequestMethod("PUT");
 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
 writer.write(tableConfig.toJSONConfigString());
 writer.flush();
 BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
 return reader.readLine().equals("done");
}
origin: Netflix/eureka

  public static String readEc2MetadataUrl(MetaDataKey metaDataKey, URL url, int connectionTimeoutMs, int readTimeoutMs) throws IOException {
    HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    uc.setConnectTimeout(connectionTimeoutMs);
    uc.setReadTimeout(readTimeoutMs);
    uc.setRequestProperty("User-Agent", "eureka-java-client");

    if (uc.getResponseCode() != HttpURLConnection.HTTP_OK) {  // need to read the error for clean connection close
      BufferedReader br = new BufferedReader(new InputStreamReader(uc.getErrorStream()));
      try {
        while (br.readLine() != null) {
          // do nothing but keep reading the line
        }
      } finally {
        br.close();
      }
    } else {
      return metaDataKey.read(uc.getInputStream());
    }

    return null;
  }
}
origin: stackoverflow.com

 URLConnection connection = new URL("https://www.google.com/search?q=" + query).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
connection.connect();

BufferedReader r  = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));

StringBuilder sb = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
  sb.append(line);
}
System.out.println(sb.toString());
origin: eclipse-vertx/vert.x

public static JsonObject getContent() throws IOException {
 URL url = new URL("http://localhost:8080");
 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 conn.connect();
 InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
 BufferedReader buff = new BufferedReader(in);
 String line;
 StringBuilder builder = new StringBuilder();
 do {
  line = buff.readLine();
  builder.append(line).append("\n");
 } while (line != null);
 buff.close();
 return new JsonObject(builder.toString());
}
origin: libgdx/libgdx

/** Returns a buffered reader for reading this file as characters.
 * @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public BufferedReader reader (int bufferSize) {
  return new BufferedReader(new InputStreamReader(read()), bufferSize);
}
origin: apache/hive

@Test
public void testStackServlet() throws Exception {
 String baseURL = "http://localhost:" + webUIPort + "/stacks";
 URL url = new URL(baseURL);
 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
 BufferedReader reader =
   new BufferedReader(new InputStreamReader(conn.getInputStream()));
 boolean contents = false;
 String line;
 while ((line = reader.readLine()) != null) {
  if (line.contains("Process Thread Dump:")) {
   contents = true;
  }
 }
 Assert.assertTrue(contents);
}
java.ioInputStreamReader

Javadoc

A class for turning a byte stream into a character stream. Data read from the source input stream is converted into characters by either a default or a provided character converter. The default encoding is taken from the "file.encoding" system property. InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed. The buffer size is 8K.

Most used methods

  • <init>
    Constructs a new InputStreamReader on the InputStream in and CharsetDecoder dec.
  • close
    Close the stream.
  • read
    Reads characters into a portion of an array.
  • getEncoding
    Returns the name of the character encoding being used by this stream. If the encoding has an histori
  • ready
    Tells whether this stream is ready to be read. An InputStreamReader is ready if its input buffer is
  • skip
  • markSupported
  • mark
  • reset
  • isOpen

Popular in Java

  • Reactive rest calls using spring rest template
  • requestLocationUpdates (LocationManager)
  • getOriginalFilename (MultipartFile)
    Return the original filename in the client's filesystem.This may contain path information depending
  • getApplicationContext (Context)
  • Pointer (com.sun.jna)
    An abstraction for a native pointer data type. A Pointer instance represents, on the Java side, a na
  • FileNotFoundException (java.io)
    Thrown when a file specified by a program cannot be found.
  • Selector (java.nio.channels)
    A controller for the selection of SelectableChannel objects. Selectable channels can be registered w
  • Queue (java.util)
    A collection designed for holding elements prior to processing. Besides basic java.util.Collection o
  • Pattern (java.util.regex)
    Patterns are compiled regular expressions. In many cases, convenience methods such as String#matches
  • IOUtils (org.apache.commons.io)
    General IO stream manipulation utilities. This class provides static utility methods for input/outpu
  • Top Vim plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now