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

How to use
BufferedReader
in
java.io

Best Java code snippets using java.io.BufferedReader (Showing top 20 results out of 100,872)

Refine searchRefine arrow

  • InputStreamReader
  • FileReader
  • URL
  • FileInputStream
  • InputStream
  • URLConnection
  • HttpResponse
  • HttpURLConnection
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

 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: libgdx/libgdx

        @Override
        public void run () {
          BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()), 1);
          try {
            int c = 0;
            while ((c = reader.read()) != -1) {
              callback.character((char)c);						
            }
          } catch (IOException e) {
//                        e.printStackTrace();
          }
        }
      });
origin: stackoverflow.com

 try(BufferedReader br = new BufferedReader(new FileReader(file))) {
  for(String line; (line = br.readLine()) != null; ) {
    // process the line.
  }
  // line is not visible here.
}
origin: stackoverflow.com

 String contentType = connection.getHeaderField("Content-Type");
String charset = null;

for (String param : contentType.replace(" ", "").split(";")) {
  if (param.startsWith("charset=")) {
    charset = param.split("=", 2)[1];
    break;
  }
}

if (charset != null) {
  try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {
    for (String line; (line = reader.readLine()) != null;) {
      // ... System.out.println(line) ?
    }
  }
} else {
  // It's likely binary content, use InputStream/OutputStream.
}
origin: stackoverflow.com

 BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
  StringBuilder sb = new StringBuilder();
  String line = br.readLine();

  while (line != null) {
    sb.append(line);
    sb.append(System.lineSeparator());
    line = br.readLine();
  }
  String everything = sb.toString();
} finally {
  br.close();
}
origin: eugenp/tutorials

  private String bodyToString(InputStream body) throws IOException {
    StringBuilder builder = new StringBuilder();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8));
    String line = bufferedReader.readLine();
    while (line != null) {
      builder.append(line).append(System.lineSeparator());
      line = bufferedReader.readLine();
    }
    bufferedReader.close();
    return builder.toString();
  }
}
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: 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: loklak/loklak_server

public static JSONArray readJsonFromUrl(String url) throws IOException, JSONException {
  InputStream is = new URL(url).openStream();
  try {
    BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
    String jsonText = readAll(rd);
    JSONArray json = new JSONArray(jsonText);
    return json;
  } finally {
    is.close();
  }
}
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

 private static String getValue(Part part) throws IOException {
  BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
  StringBuilder value = new StringBuilder();
  char[] buffer = new char[1024];
  for (int length = 0; (length = reader.read(buffer)) > 0;) {
    value.append(buffer, 0, length);
  }
  return value.toString();
}
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: 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: 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;
}
java.ioBufferedReader

Javadoc

Wraps an existing Reader and buffers the input. Expensive interaction with the underlying reader is minimized, since most (smaller) requests can be satisfied by accessing the buffer alone. The drawback is that some extra space is required to hold the buffer and that copying takes place when filling that buffer, but this is usually outweighed by the performance benefits.

A typical application pattern for the class looks like this:

 
BufferedReader buf = new BufferedReader(new FileReader("file.java")); 

Most used methods

  • <init>
    Creates a buffering character-input stream that uses an input buffer of the specified size.
  • readLine
    Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carr
  • close
    Closes this reader. This implementation closes the buffered source reader and releases the buffer. N
  • read
    Reads characters into a portion of an array. This method implements the general contract of the corr
  • lines
  • ready
    Tells whether this stream is ready to be read. A buffered character stream is ready if the buffer is
  • reset
    Resets the stream to the most recent mark.
  • mark
    Marks the present position in the stream. Subsequent calls to reset() will attempt to reposition the
  • skip
    Skips characters.
  • markSupported
    Tells whether this stream supports the mark() operation, which it does.
  • checkNotClosed
  • chompNewline
    Peeks at the next input character, refilling the buffer if necessary. If this character is a newline
  • checkNotClosed,
  • chompNewline,
  • fillBuf,
  • isClosed,
  • maybeSwallowLF,
  • readChar,
  • fill,
  • ensureOpen,
  • read1

Popular in Java

  • Reading from database using SQL prepared statement
  • scheduleAtFixedRate (Timer)
  • setScale (BigDecimal)
  • orElseThrow (Optional)
    Return the contained value, if present, otherwise throw an exception to be created by the provided s
  • Graphics2D (java.awt)
    This Graphics2D class extends the Graphics class to provide more sophisticated control overgraphics
  • RandomAccessFile (java.io)
    Allows reading from and writing to a file in a random-access manner. This is different from the uni-
  • Format (java.text)
    The base class for all formats. This is an abstract base class which specifies the protocol for clas
  • TreeMap (java.util)
    Walk the nodes of the tree left-to-right or right-to-left. Note that in descending iterations, next
  • ReentrantLock (java.util.concurrent.locks)
    A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor
  • LoggerFactory (org.slf4j)
    The LoggerFactory is a utility class producing Loggers for various logging APIs, most notably for lo
  • 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