下面列出了java.io.InputStreamReader#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Set<String> readSensitiveWord(InputStream in,Charset charset) throws Exception{
Set<String> set = new HashSet<String>();
InputStreamReader read = new InputStreamReader(in,charset);
try {
BufferedReader bufferedReader = new BufferedReader(read);
String txt = null;
while((txt = bufferedReader.readLine()) != null){ //读取文件,将文件内容放入到set中
set.add(txt);
}
} catch (Exception e) {
throw e;
}finally{
read.close(); //关闭文件流
}
return set;
}
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
textmsg.setText(s);
//Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
private String readFileContents(String filePath) {
try {
InputStream in = new FileInputStream(new File(filePath));
InputStreamReader isr = new InputStreamReader(in);
StringWriter sw = new StringWriter();
int DEFAULT_BUFFER_SIZE = 1024 * 4;
char[] buffer = new char[DEFAULT_BUFFER_SIZE];
int n = 0;
while (-1 != (n = isr.read(buffer))) {
sw.write(buffer, 0, n);
}
isr.close();
return sw.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public TestSWFParser(String name) {
super(name);
for (int i = 0; i < sampleFiles.length; i++) {
try {
// read the test string
FileInputStream fis = new FileInputStream(sampleDir + fileSeparator + sampleTexts[i]);
StringBuffer sb = new StringBuffer();
int len = 0;
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
char[] buf = new char[1024];
while ((len = isr.read(buf)) > 0) {
sb.append(buf, 0, len);
}
isr.close();
sampleTexts[i] = sb.toString().replaceAll("[ \t\r\n]+", " ").trim();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Gets the body of the response as a JSON string. When this method is called, the response's body will be read and
* the response will be disconnected, meaning that the stream returned by {@link #getBody} can no longer be used.
* @return the body of the response as a JSON string.
*/
public String getJSON() {
if (this.jsonObject != null) {
return this.jsonObject.toString();
} else {
InputStreamReader reader = new InputStreamReader(this.getBody(), StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[BUFFER_SIZE];
try {
int read = reader.read(buffer, 0, BUFFER_SIZE);
while (read != -1) {
builder.append(buffer, 0, read);
read = reader.read(buffer, 0, BUFFER_SIZE);
}
this.disconnect();
reader.close();
} catch (IOException e) {
throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
}
this.jsonObject = JsonObject.readFrom(builder.toString());
return builder.toString();
}
}
public SampleTweet() throws IOException {
ObjectMapper om = new ObjectMapper();
JsonFactory factory = new JsonFactory();
ImmutableList.Builder<String> b = ImmutableList.builder();
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("sample_tweet.json"));
try {
String tweetArray = CharStreams.toString(reader);
ArrayNode parsed = (ArrayNode)om.readTree(tweetArray);
for (JsonNode tweet : parsed) {
StringWriter sw = new StringWriter();
om.writeTree(factory.createGenerator(sw), tweet);
b.add(sw.toString());
}
sampleTweet = Iterators.cycle(b.build());
} finally {
reader.close();
}
}
private List<List<String>> readCurrenciesFromAsset() {
try {
InputStreamReader r = new InputStreamReader(context.getAssets().open("currencies.csv"), "UTF-8");
try {
Csv.Reader csv = new Csv.Reader(r).delimiter(',').ignoreComments(true).ignoreEmptyLines(true);
List<List<String>> allLines = new ArrayList<List<String>>();
List<String> line;
while ((line = csv.readLine()) != null) {
if (line.size() == 6) {
allLines.add(line);
}
}
return allLines;
} finally {
r.close();
}
} catch (IOException e) {
Log.e("Financisto", "IO error while reading currencies", e);
Toast.makeText(context, e.getClass() + ":" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
return Collections.emptyList();
}
private static void generateStringWzFile(String filePath, int depth) throws IOException {
fileReader = new InputStreamReader(new FileInputStream(wzPath + filePath), "UTF-8");
bufferedReader = new BufferedReader(fileReader);
printWriter = new PrintWriter(outputWzPath + filePath, "UTF-8");
currentDepth = 2 + depth;
//System.out.println(filePath + " depth " + depth);
generateStringWzEntry();
printWriter.close();
bufferedReader.close();
fileReader.close();
}
@Override
public String jsBridgeHelperScript() {
StringWriter writer = new StringWriter();
InputStream inputStream = getJsBridgeHelperAsStream();
InputStreamReader reader = new InputStreamReader(inputStream);
writer.append("var markdownNavigator;");
DevToolsDebuggerJsBridge.this.jsBridgeHelperScriptPrefix(writer);
try {
char[] buffer = new char[4096];
int n;
while (-1 != (n = reader.read(buffer))) {
writer.write(buffer, 0, n);
}
reader.close();
inputStream.close();
} catch (IOException e) {
LOG.error("jsBridgeHelperScript: exception", e);
}
DevToolsDebuggerJsBridge.this.jsBridgeHelperScriptSuffix(writer);
// log in the injection script and with debug break on load seems to be unstable
//writer.append('\n')
//writer.append("console.log(\"markdownNavigator: %cInjected\", \"color: #bb002f\");")
appendStateString(writer);
return writer.toString();
}
/**
* Base override. Executes the codelet
* @param inData the input data
* @param inParams a list of input parameters
* @param outParams a list of output parameters
* @return the completed output data for the workitem
* @throws CodeletExecutionException
*/
public Element execute(Element inData, List<YParameter> inParams,
List<YParameter> outParams) throws CodeletExecutionException {
final int BUF_SIZE = 8192;
setInputs(inData, inParams, outParams);
List<String> cmd = createCommandList((String) getParameterValue("command"));
StringWriter out = new StringWriter(BUF_SIZE);
try {
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
handleOptionalParameters(pb, inData); // env and working dir
_proc = pb.start();
// get the result of the process execution
InputStream is = _proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
char[] buffer = new char[BUF_SIZE];
int count;
while ((count = isr.read(buffer)) > 0)
out.write(buffer, 0, count);
isr.close();
// set and return the output
setParameterValue("result", out.toString());
return getOutputData();
}
catch (Exception e) {
throw new CodeletExecutionException("Exception executing shell process '" +
cmd + "': " + e.getMessage());
}
}
/**
*
* {@link org.apache.commons.vfs2.provider.sftp.SftpFileSystem#executeCommand(java.lang.String, java.lang.StringBuilder) }
*/
private int executeCommand( String command, StringBuilder output ) throws JSchException, IOException {
this.ensureSession();
ChannelExec channel = (ChannelExec) this.session.openChannel( "exec" );
channel.setCommand( command );
channel.setInputStream( (InputStream) null );
InputStreamReader stream = new InputStreamReader( channel.getInputStream() );
channel.setErrStream( System.err, true );
channel.connect();
char[] buffer = new char[128];
int read;
while ( ( read = stream.read( buffer, 0, buffer.length ) ) >= 0 ) {
output.append( buffer, 0, read );
}
stream.close();
while ( !channel.isClosed() ) {
try {
Thread.sleep( 100L );
} catch ( Exception exc ) {
log.logMinimal( "Warning: Error session closing. " + exc.getMessage() );
}
}
channel.disconnect();
return channel.getExitStatus();
}
public static String getVideoJsonStr() throws UnsupportedEncodingException {
String requestUrl = "http://gank.io/api/data/%E4%BC%91%E6%81%AF%E8%A7%86%E9%A2%91/10/1";
StringBuffer buffer = null;
try {
// 建立连接
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoInput(true);
httpUrlConn.setRequestMethod("GET");
// 获取输入流
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// 读取返回结果
buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
httpUrlConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
//返回获取的json字符串
if (buffer != null) {
return buffer.toString(); //返回获取的json字符串
} else {
return "";
}
}
private Map<String, String> loadCurrencyNames() throws Exception {
logger.info("loading currency names");
ClassPathResource classPathResource = new ClassPathResource("usable-currencies.json");
InputStreamReader reader = new InputStreamReader(classPathResource.getInputStream());
try {
return new ObjectMapper().readValue(classPathResource.getInputStream(), new TypeReference<Map<String, String>>() {});
} finally {
reader.close();
}
}
public static String getSearchJsonStr(String keywordStr) throws UnsupportedEncodingException {
// String requestUrl = "http://gank.io/api/search/query/listview/category/"
// + URLEncoder.encode(gankClassStr, "utf-8") + "/count/30/page/1 ";
String requestUrl = "http://gank.io/api/search/query/"
+ URLEncoder.encode(keywordStr, "utf-8") + "/category/all/count/50/page/1";
StringBuffer buffer = null;
try {
// 建立连接
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoInput(true);
httpUrlConn.setRequestMethod("GET");
// 获取输入流
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// 读取返回结果
buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
httpUrlConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
if (buffer != null) {
return buffer.toString(); //返回获取的json字符串
} else {
return "";
}
}
/**
* Performs a get on urlAsString using username and password as credentials.
* <p>
* If the status code returned not -1 and 401 then the contents are returned. If the status code is 401 an
* AuthenticationException is thrown.
* <p>
* All other values of status code are not dealt with but logic can be added as needed.
*
* @param urlAsString
* @param username
* @param password
* @return
* @throws AuthenticationException
* @throws IOException
*/
public String get( String urlAsString, String username, String password )
throws IOException, AuthenticationException {
HttpClient httpClient;
HttpGet getMethod = new HttpGet( urlAsString );
if ( !Utils.isEmpty( username ) ) {
HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder();
clientBuilder.setCredentials( username, password );
httpClient = clientBuilder.build();
} else {
httpClient = HttpClientManager.getInstance().createDefaultClient();
}
HttpResponse httpResponse = httpClient.execute( getMethod );
int statusCode = httpResponse.getStatusLine().getStatusCode();
StringBuilder bodyBuffer = new StringBuilder();
if ( statusCode != -1 ) {
if ( statusCode != HttpStatus.SC_UNAUTHORIZED ) {
// the response
InputStreamReader inputStreamReader = new InputStreamReader( httpResponse.getEntity().getContent() );
int c;
while ( ( c = inputStreamReader.read() ) != -1 ) {
bodyBuffer.append( (char) c );
}
inputStreamReader.close();
} else {
throw new AuthenticationException();
}
}
// Display response
return bodyBuffer.toString();
}
/**
* Load an object from the provided URI.
*
* @param uri location of persistent object
* @return object from location
* @throws IOException
*/
public Object load(URI uri) throws IOException {
InputStreamReader src = null;
try {
src = new FileReader(new File(uri));
return xstream.fromXML(src);
} finally {
if (null != src) {
src.close();
}
}
}
@Test
public void testGenerateAlerts() throws Exception {
InputStreamReader alertsConfigReader =
new InputStreamReader(TestEntitiesGenerator.getTestAlertsConfigStream());
int numberOfAlerts = 0;
try {
JsonObject alertsConfig = new JsonParser().parse(alertsConfigReader).getAsJsonObject();
numberOfAlerts = alertsConfig.getAsJsonArray(ConfigTags.ALERTS).size();
Set<Long> cids = new HashSet<Long>();
alertProcessor.generateAlerts(cids, alertsConfig);
} finally {
alertsConfigReader.close();
}
verify(alertProcessor, times(numberOfAlerts)).processAlert(
Mockito.<Set<Long>>anyObject(),
Mockito.<ImmutableAdWordsSession>anyObject(),
Mockito.<JsonObject>anyObject(),
Mockito.anyInt());
verify(alertProcessor, times(numberOfAlerts)).downloadReports(
Mockito.<ImmutableAdWordsSession>anyObject(),
Mockito.<Set<Long>>anyObject(),
Mockito.<JsonObject>anyObject());
verify(alertProcessor, times(numberOfAlerts)).processReports(
reportsCaptor.capture(),
Mockito.<JsonArray>anyObject(),
Mockito.anyString(),
Mockito.<JsonArray>anyObject());
}
private static void readQuestsWithMissingScripts() throws IOException {
String line;
fileReader = new InputStreamReader(new FileInputStream(checkName), "UTF-8");
bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
translateTokenCheck(line);
}
bufferedReader.close();
fileReader.close();
}
public void doTranslate() throws IOException, JSONException {
// 格式化需要翻译的内容为UTF-8编码
String str_utf = URLEncoder.encode(str, "UTF-8");
// 百度翻译api
String str_url = "http://openapi.baidu.com/public/2.0/bmt/translate?client_id=GOr7jiTs5hiQvkHqDNg4KSTV&q="
+ str_utf + "&from=" + fromString + "&to=" + toString;
// 将api网址转化成URL
URL url_word = new URL(str_url);
// 连接到该URL
URLConnection connection = (URLConnection) url_word.openConnection();
// 获取输入流
InputStream is = connection.getInputStream();
// 转化成读取流
InputStreamReader isr = new InputStreamReader(is);
// 转化成缓冲读取流
BufferedReader br = new BufferedReader(isr);
// 每行的内容
String line;
// 字符串处理类
StringBuilder sBuilder = new StringBuilder();
// 读取每行内容
while ((line = br.readLine()) != null) {
// 在字符串末尾追加内容
sBuilder.append(line);
}
/**
* 单词解析
*/
JSONTokener jtk = new JSONTokener(sBuilder.toString());
JSONObject jObject = (JSONObject) jtk.nextValue();
JSONArray jArray = jObject.getJSONArray("trans_result");
Log.i("TAG", url_word.toString());
Log.i("TAG", jObject.toString());
JSONObject sub_jObject_1 = jArray.getJSONObject(0);
// dst对应的内容就是翻译结果
result = sub_jObject_1.getString("dst");
br.close();
isr.close();
is.close();
}
public static void main(String[] args)
{
ExecutorService exec = Executors.newFixedThreadPool(30);
for (int index = 0; index < 100; index++)
{
final int NO = index;
Runnable run = new Runnable()
{
public void run()
{
try
{
long time1 = System.currentTimeMillis();
URL url = new URL("http://192.168.0.102:8080/albert/lab/mutiThreads");
InputStreamReader isr = new InputStreamReader(url.openStream());
long time2 = System.currentTimeMillis();
System.out.print("Thread " + NO + " time:" + (time2 - time1) + "ms");
BufferedReader br = new BufferedReader(isr);
String str;
while ((str = br.readLine()) != null)
{
System.out.println(str);
}
br.close();
isr.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
exec.execute(run);
}
// 退出线程池
exec.shutdown();
}