Java Code Examples for java.io.InputStreamReader.close()

The following are Jave code examples for showing how to use close() of the java.io.InputStreamReader class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: awe-awesomesky   File: HttpUtil.java   View Source Code Vote up 8 votes
public void doGet(String url) throws Exception{
	URL localURL = new URL(url);
	URLConnection con = openConnection(localURL);
	HttpURLConnection httpCon = (HttpURLConnection)con;
	httpCon.setRequestProperty("Accept-Charset",CHARSET);
	httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	if(httpCon.getResponseCode()>=300){
		throw new RuntimeException("请求失败...");
	}
	InputStreamReader isr = new InputStreamReader(httpCon.getInputStream());
	BufferedReader reader = new BufferedReader(isr);
	String res = reader.readLine();
	System.out.println(res);
	isr.close();
	reader.close();
}
 
Example 2
Project: FJ-VDMJ   File: BacktrackInputReader.java   View Source Code Vote up 7 votes
/**
 * Create an object to read the file name passed with the given charset.
 *
 * @param file	The filename to open
 */

public BacktrackInputReader(File file, String charset)
{
	try
	{
		InputStreamReader isr = readerFactory(file, charset);
		data = new char[readerLength(file, isr)];
		max = isr.read(data);
		pos = 0;
		isr.close();
	}
	catch (IOException e)
	{
		throw new InternalException(0, e.getMessage());
	}
}
 
Example 3
Project: FAIRsharing-Owl2Neo   File: ResourceFile.java   View Source Code Vote up 6 votes
public String getContent(String charSet) throws IOException {
    InputStreamReader reader = new InputStreamReader(createInputStream(),
            Charset.forName(charSet));
    char[] tmp = new char[4096];
    StringBuilder b = new StringBuilder();
    try {
        while (true) {
            int len = reader.read(tmp);
            if (len < 0) {
                break;
            }
            b.append(tmp, 0, len);
        }
        reader.close();
    } finally {
        reader.close();
    }
    return b.toString();
}
 
Example 4
Project: FJ-VDMJ   File: BacktrackInputReader.java   View Source Code Vote up 6 votes
/**
 * Create an object to read the string passed. This is used in the
 * interpreter to parse expressions typed in.
 *
 * @param expression
 */
public BacktrackInputReader(String expression, String charset)
{
   	try
       {
        ByteArrayInputStream is =
        	new ByteArrayInputStream(expression.getBytes(charset));

        InputStreamReader isr =
        	new LatexStreamReader(is, charset);

   		data = new char[expression.length() + 1];
        max = isr.read(data);
        pos = 0;

        isr.close();
        is.close();
       }
       catch (IOException e)
       {
        // This can never really happen...
       }
}
 
Example 5
Project: AOSP-Kayboard-7.1.2   File: UpdateHandler.java   View Source Code Vote up 6 votes
/**
 * Parse metadata and take appropriate action (that is, upgrade dictionaries).
 * @param context the context to read settings.
 * @param stream an input stream pointing to the downloaded data. May not be null.
 *  Will be closed upon finishing.
 * @param clientId the ID of the client to update
 * @throws BadFormatException if the metadata is not in a known format.
 * @throws IOException if the downloaded file can't be read from the disk
 */
public static void handleMetadata(final Context context, final InputStream stream,
        final String clientId) throws IOException, BadFormatException {
    DebugLogUtils.l("Entering handleMetadata");
    final List<WordListMetadata> newMetadata;
    final InputStreamReader reader = new InputStreamReader(stream);
    try {
        // According to the doc InputStreamReader buffers, so no need to add a buffering layer
        newMetadata = MetadataHandler.readMetadata(reader);
    } finally {
        reader.close();
    }

    DebugLogUtils.l("Downloaded metadata :", newMetadata);
    PrivateLog.log("Downloaded metadata\n" + newMetadata);

    final ActionBatch actions = computeUpgradeTo(context, clientId, newMetadata);
    // TODO: Check with UX how we should report to the user
    // TODO: add an action to close the database
    actions.execute(context, new LogProblemReporter(TAG));
}
 
Example 6
Project: util4j   File: SensitiveFilter.java   View Source Code Vote up 6 votes
private Set<String> readSensitiveWord(InputStream in,Charset charset) throws Exception{
	Set<String> set = new HashSet<String>();
	InputStreamReader read = new InputStreamReader(in,charset);
	try {
		set = new HashSet<String>();
		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;
}
 
Example 7
Project: Yidu   File: FileUtils.java   View Source Code Vote up 6 votes
/**
 * 根据指定编码读取文件
 * 
 * @param fileName
 *            文件名
 * @param charset
 *            字符集
 * @return 文件字符串
 */
public static String readFile(String fileName, String charset) {
    StringBuffer sb = new StringBuffer();
    File file = new File(fileName);
    try {
        InputStreamReader read = new InputStreamReader(new FileInputStream(file), charset);
        BufferedReader bufferedReader = new BufferedReader(read);
        String lineTxt = null;
        while ((lineTxt = bufferedReader.readLine()) != null) {
            sb.append(lineTxt + System.getProperty("line.separator"));
        }
        read.close();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return sb.toString();
}
 
Example 8
Project: BBSSDK-for-Android   File: OfficeConverter.java   View Source Code Vote up 6 votes
private void txtToHtml() throws Throwable {
	FileOutputStream output = new FileOutputStream(new File(htmlPath));
	String head = "<!DOCTYPE><html><head><meta charset=\"utf-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">"
			+ "<meta name=\"viewport\" content=\"initial-scale=1, maximum-scale=1\">"
			+ "</head><body style=\"background:#fff padding:10px,10px,10px,10px\"><div style=\"font-size:.66667rem color:#666\">";
	String end = "</div></body></html>";
	output.write(head.getBytes());
	InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), getCharset(filePath));
	BufferedReader br = new BufferedReader(isr);
	String line;
	while ((line = br.readLine()) != null) {
		output.write(line.getBytes());
		output.write("<br />".getBytes("UTF-8"));
	}
	br.close();
	isr.close();
	output.write(end.getBytes());
	output.close();
}
 
Example 9
Project: AndroidSerialPort   File: GPIOFileUtils.java   View Source Code Vote up 6 votes
public int getGPIOC7(){
    File file = new File("/sys/class/gpio/gpio71/value");
    try {
        InputStream instream = new FileInputStream(file);
        InputStreamReader inputreader = new InputStreamReader(instream);
        BufferedReader buffreader = new BufferedReader(inputreader);
        String c7value = buffreader.readLine();
        if(c7value == null || c7value =="")
            return -1;
        instream.close();
        inputreader.close();
        buffreader.close();
        return Integer.parseInt(c7value);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return -1;
}
 
Example 10
Project: arcadelegends-gg   File: EntityArguments.java   View Source Code Vote up 6 votes
/**
 * Parses an {@link EntityArguments} object from the given .json file
 *
 * @param name the name of the .json file
 * @return the parsed {@link EntityArguments}
 * @throws IOException
 */
public static EntityArguments fromFile(String name) throws IOException {

    EntityArguments arguments = new EntityArguments();
    InputStream is = EntityArguments.class.getResourceAsStream("/" + name);
    InputStreamReader reader = new InputStreamReader(is);
    Type type = new TypeToken<Map<String, Template>>() {
    }.getType();
    Map<String, Template> defs = GsonUtil.getGSON().fromJson(reader, type);
    reader.close();

    for (Map.Entry<String, Template> entries : defs.entrySet()) {
        arguments.put(entries.getKey(), entries.getValue());
    }
    return arguments;
}
 
Example 11
Project: PureMusic   File: LyricView.java   View Source Code Vote up 6 votes
private void setupLyricResource(InputStream inputStream, String charsetName) {
    if (inputStream != null) {
        try {
            LyricInfo lyricInfo = new LyricInfo();
            lyricInfo.songLines = new ArrayList<>();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charsetName);
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = reader.readLine()) != null) {
                analyzeLyric(lyricInfo, line);
            }
            reader.close();
            inputStream.close();
            inputStreamReader.close();

            mLyricInfo = lyricInfo;
            mLineCount = mLyricInfo.songLines.size();
            invalidateView();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        invalidateView();
    }
}
 
Example 12
Project: lembredio   File: PacienteInterface.java   View Source Code Vote up 6 votes
public LinkedList<String> retornarListaDeFarmacias() throws IOException{
    String linha;
    LinkedList<String> farmacias = new LinkedList(); 
    File file = new File("FarmaciasCadastradas.txt");
    if(!file.exists()) file.createNewFile();
    InputStream is = new FileInputStream("FarmaciasCadastradas.txt");
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    
    do{
        linha = br.readLine();
        if(linha != null) farmacias.add(linha);
    }while(linha != null);
    is.close();
    isr.close();
    br.close();
    return farmacias;

}
 
Example 13
Project: hadoop   File: TestJobEndNotifier.java   View Source Code Vote up 6 votes
@Override
public void doGet(HttpServletRequest request, 
                  HttpServletResponse response
                  ) throws ServletException, IOException {
  InputStreamReader in = new InputStreamReader(request.getInputStream());
  PrintStream out = new PrintStream(response.getOutputStream());

  calledTimes++;
  try {
    requestUri = new URI(null, null,
        request.getRequestURI(), request.getQueryString(), null);
  } catch (URISyntaxException e) {
  }

  in.close();
  out.close();
}
 
Example 14
Project: os   File: SensitiveWordInit.java   View Source Code Vote up 6 votes
/**
 * 读取敏感词库中的内容,将内容添加到set集合中
 * @author chenssy 
 * @date 2014年4月20日 下午2:31:18
 * @return
 * @version 1.0
 * @throws Exception 
 */
@SuppressWarnings("resource")
private Set<String> readSensitiveWordFile() throws Exception{
	Set<String> set = null;
	
	File file = new File("D:\\SensitiveWord.txt");    //读取文件
	InputStreamReader read = new InputStreamReader(new FileInputStream(file),ENCODING);
	try {
		if(file.isFile() && file.exists()){      //文件流是否存在
			set = new HashSet<String>();
			BufferedReader bufferedReader = new BufferedReader(read);
			String txt = null;
			while((txt = bufferedReader.readLine()) != null){    //读取文件,将文件内容放入到set中
				set.add(txt);
		    }
		}
		else{         //不存在抛出异常信息
			throw new Exception("敏感词库文件不存在");
		}
	} catch (Exception e) {
		throw e;
	}finally{
		read.close();     //关闭文件流
	}
	return set;
}
 
Example 15
Project: Cable-Android   File: PreKeyUtil.java   View Source Code Vote up 6 votes
private static synchronized int getNextSignedPreKeyId(Context context) {
  try {
    File nextFile = new File(getSignedPreKeysDirectory(context), SignedPreKeyIndex.FILE_NAME);

    if (!nextFile.exists()) {
      return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
    } else {
      InputStreamReader reader = new InputStreamReader(new FileInputStream(nextFile));
      SignedPreKeyIndex index  = JsonUtils.fromJson(reader, SignedPreKeyIndex.class);
      reader.close();
      return index.nextSignedPreKeyId;
    }
  } catch (IOException e) {
    Log.w("PreKeyUtil", e);
    return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
  }
}
 
Example 16
Project: tensorflow-hangul-recognition   File: HangulTranslator.java   View Source Code Vote up 5 votes
/**
 * This is an asynchronously called function, that will send an HTTP POST request to the
 * translator endpoint with the Korean text in the request.
 * @return String response from the translator service.
 */
@Override
protected String doInBackground(String... params) {

    String result = "";

    try {
        URL url = new URL(TRANSLATE_API_ENDPOINT);
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");

        // Set authorization header.
        String authString = this.username + ":" + this.password;
        byte[] base64Bytes = Base64.encode(authString.getBytes(), Base64.DEFAULT);
        String base64String = new String(base64Bytes);
        urlConnection.setRequestProperty("Authorization", "Basic " + base64String);

        if (this.postData != null) {
            OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
            writer.write(postData.toString());
            writer.flush();
            writer.close();
        }

        int statusCode = urlConnection.getResponseCode();
        if (statusCode ==  200) {
            InputStreamReader streamReader = new InputStreamReader(
                    urlConnection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(streamReader);

            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = bufferedReader.readLine()) != null) {
                response.append(inputLine);
            }
            streamReader.close();
            bufferedReader.close();
            result = response.toString();
        }
        else {
            System.out.println("Error translating. Response Code: " + statusCode);
        }
    }
    catch (Exception e) {
        System.out.println(e.getMessage());

    }
    return result;
}
 
Example 17
Project: SkyDocs   File: GithubUpdater.java   View Source Code Vote up 5 votes
@Override
public final void run() {
	caller.updaterStarted();
	try {
		final HttpURLConnection connection = (HttpURLConnection)new URL("https://api.github.com/repos/" + UPDATER_GITHUB_USERNAME + "/" + UPDATER_GITHUB_REPO + "/releases/latest").openConnection();
		connection.addRequestProperty("User-Agent", UPDATER_NAME + " v" + UPDATER_VERSION);
		
		final String response = connection.getResponseCode() + " " + connection.getResponseMessage();
		caller.updaterResponse(response);
		
		final InputStream input = response.startsWith("2") ? connection.getInputStream() : connection.getErrorStream();
		final InputStreamReader inputStreamReader = new InputStreamReader(input, StandardCharsets.UTF_8);
		final BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		final JsonObject latest = Json.parse(bufferedReader.readLine()).asObject();
		input.close();
		inputStreamReader.close();
		bufferedReader.close();
		
		final String remoteVersion = latest.getString("tag_name", "v0").substring(1);
		if(compareVersions(remoteVersion, localVersion)) {
			caller.updaterUpdateAvailable(localVersion, remoteVersion);
		}
		else {
			caller.updaterNoUpdate(localVersion, remoteVersion);
		}
	}
	catch(final Exception ex) {
		ex.printStackTrace();
		caller.updaterException(ex);
	}
}
 
Example 18
Project: awe-awesomesky   File: HttpUtil.java   View Source Code Vote up 5 votes
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
	JSONObject jsonObject = null;
	try {
		// 创建SSLContext对象,并使用我们指定的信任管理器初始化
		TrustManager[] tm = { new HttpsX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();
		URL url = new URL(requestUrl);
		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
		conn.setSSLSocketFactory(ssf);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestProperty("Connection", "keep-alive");
		conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36");
		conn.setUseCaches(false);
		conn.setRequestProperty("Content-Type", "application/json;;charset=UTF-8");
		// 设置请求方式(GET/POST)
		conn.setRequestMethod(requestMethod);
		// 当outputStr不为null时向输出流写数据
		if (null != outputStr) {
			OutputStream outputStream = conn.getOutputStream();
			// 注意编码格式
			outputStream.write(outputStr.getBytes("UTF-8"));
			outputStream.close();
		}
		// 从输入流读取返回内容
		InputStream inputStream = conn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String str = null;
		StringBuffer buffer = new StringBuffer();
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		// 释放资源
		bufferedReader.close();
		inputStreamReader.close();
		inputStream.close();
		inputStream = null;
		conn.disconnect();
		jsonObject = JSONObject.parseObject(buffer.toString());
	} catch (ConnectException ce) {
		ce.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return jsonObject;
}
 
Example 19
Project: Babler   File: MyProperties.java   View Source Code Vote up 5 votes
/**
 * reads properties and stores them in the Hashtable
 * 
 * @param is InputStream reading properties
 */
public void load(InputStream is) {
	Logger log = Logger.getLogger(MyProperties.class);
	int lineCounter = 0;
	String line;
	String[] prop = new String[2];
	int i;
	InputStreamReader isr = new InputStreamReader(is);
	BufferedReader br = new BufferedReader(isr);
	try {
		while ((line = br.readLine()) != null) {
			lineCounter++;
			i = 0;
			line = line.replaceAll("<","_").replaceAll(">","_");
			String[] tokens = line.split("\\s");
			for(String token : tokens) {
				if(!token.equals("")) {
					prop[i] = token;
					i++;
					if(i == 2) {
						break;
					}
				}
			}
			this.put(prop[0],prop[1]);
		}
		br.close();
		isr.close();
	} catch (IOException ioe) {
		log.error(ioe);
	}
}
 
Example 20
Project: incubator-netbeans   File: ColorModel.java   View Source Code Vote up 4 votes
private String [] loadPreviewExample(String mimeType) {
    FileObject exampleFile = null;
    String exampleMimeType = null;
    
    if (mimeType == null || mimeType.length() == 0) {
        FileObject f = FileUtil.getConfigFile("OptionsDialog/PreviewExamples"); //NOI18N
        if (f != null && f.isFolder()) {
            FileObject [] ff = f.getChildren();
            for(int i = 0 ; i < ff.length; i++) {
                if (ff[i].isData()) {
                    exampleFile = ff[i];
                    break;
                }
            }
        }
        if (exampleFile != null) {
            if (exampleFile.getMIMEType().equals("content/unknown")) { //NOI18N
                exampleMimeType = "text/x-all-languages"; //NOI18N
            } else {
                exampleMimeType = exampleFile.getMIMEType();
            }
        }
    } else {
        exampleFile = FileUtil.getConfigFile("OptionsDialog/PreviewExamples/" + mimeType); //NOI18N
        exampleMimeType = mimeType;
    }
    
    if (exampleFile != null && exampleFile.isValid() && exampleFile.getSize() > 0) {
        StringBuilder sb;
        if (exampleFile.getSize() < (long) Integer.MAX_VALUE) {
            sb = new StringBuilder((int)exampleFile.getSize());
        } else {
            sb = new StringBuilder(Integer.MAX_VALUE);
        }
            
        
        try {
            InputStreamReader is = new InputStreamReader(exampleFile.getInputStream());
            char [] buffer = new char[1024];
            int size;
            try {
                while(0 < (size = is.read(buffer, 0, buffer.length))) {
                    sb.append(buffer, 0, size);
                }
            } finally {
                is.close();
            }
        } catch (IOException ioe) {
            LOG.log(Level.WARNING, "Can't read font & colors preview example", ioe); //NOI18N
        }
        
        return new String [] { sb.toString(), exampleMimeType };
    } else {
        if(exampleFile != null && !exampleFile.isValid()) {
            LOG.log(Level.WARNING, "Font & colors preview example is invalid " + exampleFile); //NOI18N
        }
        return new String [] { "", "text/plain" }; //NOI18N
    }            
}