Java Code Examples for java.io.BufferedReader#close()

The following examples show how to use java.io.BufferedReader#close() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: xnx3   File: PingxxUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * ping++异步回调传回的参数,直接调用此方法,拿到值
 * @param request {@link HttpServletRequest}
 * @param response {@link HttpServletResponse}
 * @return 若成功,返回 {@link com.xnx3.j2ee.module.pingxx.bean.Event} 若失败,返回null
 * @throws IOException
 */
public static com.xnx3.j2ee.module.pingxx.bean.Event webhooks(HttpServletRequest request,HttpServletResponse response) throws IOException{
	request.setCharacterEncoding("UTF8");
    // 获得 http body 内容
    BufferedReader reader = request.getReader();
    StringBuffer buffer = new StringBuffer();
    String string;
    while ((string = reader.readLine()) != null) {
        buffer.append(string);
    }
    reader.close();
    
    String sign = request.getHeader("X-Pingplusplus-Signature");	//签名
    String dataString = buffer.toString();
    com.xnx3.j2ee.module.pingxx.bean.Event event = getEventByContent(dataString, sign);
	return event;
}
 
Example 2
@Override
public void setUp() throws IOException {
    empiricalDistribution = new EmpiricalDistributionImpl(100);
    url = getClass().getResource("testData.txt");
    
    empiricalDistribution2 = new EmpiricalDistributionImpl(100);
    BufferedReader in = 
            new BufferedReader(new InputStreamReader(
                    url.openStream()));
    String str = null;
    ArrayList<Double> list = new ArrayList<Double>();
    while ((str = in.readLine()) != null) {
        list.add(Double.valueOf(str));
    }
    in.close();
    in = null;
    
    dataArray = new double[list.size()];
    int i = 0;
    for (Double data : list) {
        dataArray[i] = data.doubleValue();
        i++;
    }                 
}
 
Example 3
Source Project: mustard   File: RESCALOutput.java    License: MIT License 6 votes vote down vote up
public void loadAttributeEmb(String filename, Map<Integer, Pair<URI,Literal>> invAttributeMap) {
	try {
		BufferedReader fr = new BufferedReader(new FileReader(filename));
		String line;

		for (int i = 0; (line = fr.readLine()) != null; i++) {
			int numFacs = line.split(" ").length;
			double[] facs = new double[numFacs];
			attributeEmb.put(invAttributeMap.get(i), facs);

			int j = 0;
			for (String val : line.split(" ")) {
				facs[j] = Double.parseDouble(val);
				j++;
			}

		}
		fr.close();

	} catch (Exception e) {
		throw new RuntimeException(e);		
	}
}
 
Example 4
private void printStackTrace(int pid) {
    try {
        ProcessBuilder pb = new ProcessBuilder(getJavaTool("jstack").getAbsolutePath(), "" + pid);
        pb.redirectErrorStream(true);
        Process p = pb.start();

        Reader r = new InputStreamReader(p.getInputStream());
        BufferedReader br = new BufferedReader(r);

        String line;
        while ((line = br.readLine()) != null) {
            System.err.println(line);
        }

        br.close();
        r.close();
    } catch (Exception e) {
        System.err.println("Cannot print stack trace of the process with pid " + pid);
    }
}
 
Example 5
Source Project: kylin   File: AppendTrieDictionaryTest.java    License: Apache License 2.0 6 votes vote down vote up
private static ArrayList<String> loadStrings(InputStream is) throws Exception {
    ArrayList<String> r = new ArrayList<String>();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    try {
        String word;
        while ((word = reader.readLine()) != null) {
            word = word.trim();
            if (word.isEmpty() == false)
                r.add(word);
        }
    } finally {
        reader.close();
        is.close();
    }
    return r;
}
 
Example 6
Source Project: HubPlayer   File: LrcInfos.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void read(File file) {

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(file), "utf-8"));

			String line = "";

			while ((line = reader.readLine()) != null) {
				match(line);
			}

			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
 
Example 7
Source Project: OpenDL   File: DataInput.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Read sample data from mnist_784 text file 
 * @param path
 * @return
 * @throws Exception
 */
public static List<SampleVector> readMnist(String path, int x_feature, int y_feature) throws Exception {
	List<SampleVector> ret = new ArrayList<SampleVector>();
	String str = null;
       BufferedReader br = new BufferedReader(new FileReader(path));
       while (null != (str = br.readLine())) {
           String[] splits = str.split(",");
           SampleVector xy = new SampleVector(x_feature, y_feature);
           xy.getY()[Integer.valueOf(splits[0])] = 1;
           for (int i = 1; i < splits.length; i++) {
               xy.getX()[i - 1] = Double.valueOf(splits[i]);
           }
           ret.add(xy);
       }
       br.close();
	return ret;
}
 
Example 8
public void processStream(InputStream stream) throws IOException,
    InterruptedException {
  BufferedReader br =
      new BufferedReader(new InputStreamReader(stream, "UTF8"));
  String line = null;
  try {
    line = br.readLine();
    while (line != null) {
      if (line.startsWith("#") || line.trim().equals("")) {
        line = br.readLine();
        continue;
      }
      JsonObject jsonSentence = jsonParser.parse(line).getAsJsonObject();
      processSentence(jsonSentence);
      line = br.readLine();
    }
  } catch (Exception e) {
    System.err.println("Could not process line: ");
    System.err.println(line);
  } finally {
    br.close();
  }
}
 
Example 9
Source Project: blog   File: Main.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	String path = Main.class.getResource("/data.txt").getPath();
	FileReader fileReader = new FileReader(path);
	BufferedReader bufferedReader = new BufferedReader(fileReader); // 使用委托的方式实现适配器模式
	System.out.println(bufferedReader.readLine());

	bufferedReader.close();
	fileReader.close();
}
 
Example 10
@Test
public void forceUnshelveStringConstructor() throws Throwable {
    UnshelveFilesOptions unshelveFilesOptions = new UnshelveFilesOptions("-f");

    client.unshelveFiles(clobberFileSpecs, pendingChangelist.getId(), pendingChangelist.getId(), unshelveFilesOptions);

    List<IExtendedFileSpec> extendedFileSpecs = h.getExtendedFileSpecs(server, clobberFileSpecs, pendingChangelist.getId());

    assertEquals(1, extendedFileSpecs.size());
    assertEquals(VALID, extendedFileSpecs.get(0).getOpStatus());

    BufferedReader bufferedReader = new BufferedReader(new FileReader(clobberFile));
    assertEquals("UnshelveFilesOptions", bufferedReader.readLine());
    bufferedReader.close();
}
 
Example 11
Source Project: Deta_Parser   File: FMHMMListOneTimeImp.java    License: Apache License 2.0 5 votes vote down vote up
public void indexGm() throws IOException {
	listGm = new CopyOnWriteArrayList<>();
	InputStream in = getClass().getResourceAsStream(StableData.WORDS_SOURSE_LINK_POS_CN_TO_GM);
	BufferedReader cReader = new BufferedReader(new InputStreamReader(in, StableData.UTF8_STRING));
	String cInputString;
		while (null!= (cInputString = cReader.readLine())) {
			listGm.add(cInputString);
		}
	cReader.close();
}
 
Example 12
Source Project: netbeans   File: SCFTHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
private static String readChars(FileObject fo, Charset set) throws IOException {
    CharBuffer arr = CharBuffer.allocate((int)fo.getSize() * 2);
    BufferedReader r = new BufferedReader(new InputStreamReader(fo.getInputStream(), set));
    while (r.read(arr) != -1) {
        // again
    }
    r.close();
    
    arr.flip();
    return arr.toString();
}
 
Example 13
public static HashMap<String, String> getInfo(File outputFile) {
    try {
        BufferedReader reader = new BufferedReader(new FileReader(outputFile));
        String line = null;
        HashMap<String, String> info = new HashMap<String, String>();
        while ((line = reader.readLine()) != null) {
            int idx = line.indexOf(',');
            if (idx >= 0) {
                String key = line.substring(0, idx).trim();
                String value = line.substring(idx + 1).trim();
                if (value.indexOf('(') >= 0 && value.indexOf(')') >= 0) {
                    value = value.substring(value.indexOf('(') + 1, value.indexOf(')'));
                    if (value.indexOf('/') >= 0) {
                        String bound = value.substring(value.indexOf('/') + 1);
                        if (bound.indexOf("..") >= 0) {
                            String min = bound.substring(0, bound.indexOf(".."));
                            String max = bound.substring(bound.indexOf("..") + 2);
                            info.put(key + " Min", min);
                            info.put(key + " Max", max);
                        } else {
                            info.put(key + " Bound", bound);
                        }
                        value = value.substring(0, value.indexOf('/'));
                    }
                }
                if (value.length() > 0)
                    info.put(key, value);
            }
        }
        reader.close();
        return info;
    } catch (Exception e) {
        System.err.println("Error reading info, message: " + e.getMessage());
        e.printStackTrace();
        return null;
    }
}
 
Example 14
public static String exec(String cmd) throws Exception {
    String sb = "";
    BufferedInputStream in = new BufferedInputStream(Runtime.getRuntime().exec(cmd).getInputStream());
    BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
    String lineStr;
    while ((lineStr = inBr.readLine()) != null)
        sb += lineStr + "\n";
    inBr.close();
    in.close();
    return sb;
}
 
Example 15
/**
 * Sends the data to the bStats server.
 *
 * @param plugin Any plugin. It's just used to get a logger instance.
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(Plugin plugin, JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    if (logSentData) {
        plugin.getLogger().info("Sending data to bStats: " + data.toString());
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    InputStream inputStream = connection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        builder.append(line);
    }
    bufferedReader.close();
    if (logResponseStatusText) {
        plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
    }
}
 
Example 16
public void loadTextDefinitionFile(File textDefinitionFile) throws FileNotFoundException, IOException {
    System.out.println("Starting Text Definitions: " + textDefinitionFile.getName());
    File output=sortFile(textDefinitionFile, tmpFolder, tmpOutputFileSortedFolder, new int[]{0,1});
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(output), "UTF8"));
    int descriptionsCount = 0;
    try {
        String line = br.readLine();
        line = br.readLine(); // Skip header
        boolean act;
        while (line != null) {
            if (line.isEmpty()) {
                continue;
            }
            String[] columns = line.split("\\t");
            LightDescription loopDescription = new LightDescription();
            loopDescription.setDescriptionId(Long.parseLong(columns[0]));
            act = columns[2].equals("1");
            loopDescription.setActive(act);
            loopDescription.setEffectiveTime(columns[1]);
            loopDescription.setScTime(MAXEFFTIME);
            Long sourceId = Long.parseLong(columns[4]);
            loopDescription.setConceptId(sourceId);
            loopDescription.setType(Long.parseLong(columns[6]));
            loopDescription.setTerm(columns[7]);
            loopDescription.setIcs(Long.parseLong(columns[8]));
            loopDescription.setModule(Long.parseLong(columns[3]));
            loopDescription.setLang(columns[5]);
            List<LightDescription> list = tdefMembers.get(sourceId);
            if (list == null) {
                list = new ArrayList<LightDescription>();
            }else{
            	
            	for (LightDescription item:list){
            		if (item.getDescriptionId().equals(loopDescription.getDescriptionId()) && item.getScTime().equals(MAXEFFTIME)){
            			item.setScTime(columns[1]);
            		}
            	}
            }
            list.add(loopDescription);
            tdefMembers.put(sourceId, list);

            line = br.readLine();
            descriptionsCount++;
            if (descriptionsCount % 100000 == 0) {
                System.out.print(".");
            }
        }
        System.out.println(".");
        System.out.println("Text Definitions loaded = " + tdefMembers.size());
    } finally {
        br.close();
    }
}
 
Example 17
private boolean writeToFileFrom(String writingFileName, InputStream fromInStream)
{
	boolean success=false;
	File writingFile=new File(FileItemContainer.getTextStorageDir(),writingFileName);
	
       try {
       	BufferedReader br=new BufferedReader(new InputStreamReader(fromInStream));
       	
           FileOutputStream f = new FileOutputStream(writingFile);
           PrintWriter pw = new PrintWriter(f);
           
           String text=null;
           int lineCount=0;
           while((text=br.readLine()) != null)
           {
               pw.append(text).append("\n");
               lineCount++;
           }
           
           if(lineCount>=totalAyahs){//validity check
           
            pw.flush();           
            pw.close();
            
            success=true;
            //Toast.makeText(this,"Saved Successfully :\n"+toFile.getName(), Toast.LENGTH_LONG).show();
            addToFileItems(writingFile);
            f.close();
           }else{
           	if(writingFile.exists())
           		writingFile.delete();
           }

           fromInStream.close();
           br.close();
           
       } catch (IOException e) {
       	e.printStackTrace();
       }
       
       return success;
}
 
Example 18
@BeforeClass
public static void getAccessTokenUsingPasswordGrant() throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, JSONException {
    URL url = new URL(TOKEN_ENDPOINT);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    String urlParameters = String.format(
            "grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s",
            GRANT_TYPE,
            URLEncoder.encode(ServiceConstants.AUTHENTICATION_RESOURCE_ID, "UTF-8"),
            clientId,
            username,
            password
    );

    connection.setRequestMethod(REQUEST_METHOD);
    connection.setRequestProperty("Content-Type", CONTENT_TYPE);
    connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes("UTF-8").length));

    connection.setDoOutput(true);
    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.writeBytes(urlParameters);
    dataOutputStream.flush();
    dataOutputStream.close();

    connection.getResponseCode();

    BufferedReader in = new BufferedReader(
            new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    JsonParser jsonParser = new JsonParser();
    JsonObject grantResponse = (JsonObject)jsonParser.parse(response.toString());
    accessToken = grantResponse.get("access_token").getAsString();

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    request = request.newBuilder()
                            .addHeader("Authorization", "Bearer " + accessToken)
                            // This header has been added to identify this sample in the Microsoft Graph service.
                            // If you're using this code for your project please remove the following line.
                            .addHeader("SampleID", "android-java-snippets-rest-sample")
                            .build();

                    return chain.proceed(request);
                }
            })
            .addInterceptor(logging)
            .build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ServiceConstants.AUTHENTICATION_RESOURCE_ID)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    contactService = retrofit.create(MSGraphContactService.class);
    drivesService = retrofit.create(MSGraphDrivesService.class);
    eventsService = retrofit.create(MSGraphEventsService.class);
    groupsService = retrofit.create(MSGraphGroupsService.class);
    mailService = retrofit.create(MSGraphMailService.class);
    meService = retrofit.create(MSGraphMeService.class);
    userService = retrofit.create(MSGraphUserService.class);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.US);
    dateTime = simpleDateFormat.format(new Date());
}
 
Example 19
/** Construct a prior model with the FLM config file and corresponding vocab file. */
public POSPriorModel(String flmFile, String vocabFile) throws IOException {
    super(flmFile);
    String post = null;
    BufferedReader br = new BufferedReader(new FileReader(new File(vocabFile)));
    post = br.readLine().trim();

    // get next POS tag from the vocab.
    while ((post != null) && !post.trim().startsWith(POS_TAG + "-")) {
        post = br.readLine();
    }
    if (post != null) {
        post = post.trim().split("-")[1];
    }

    Collection<String> allSupertags = new HashSet<String>();

    // find out how many outcomes we have.
    int cnt = 0;
    while (post != null) {
        cnt++;
        allSupertags.add(post);
        while ((post != null) && !post.trim().startsWith(POS_TAG + "-")) {
            post = br.readLine();
        }
        if (post != null) {
            post = post.trim().split("-")[1];
        }
    }

    // initialize the arrays to this size.
    posVocab = new String[cnt];
    

    cnt = 0;
    // fill the vocab array with all possible POS tags.
    for (String posTag : allSupertags) {
        posVocab[cnt++] = posTag.intern();
    }
    br.close();
}
 
Example 20
private byte[] mergeAndPersistConfig(byte[] currentConfigBytes) throws IOException {
	String currentCfgStr = new String(currentConfigBytes);
	boolean filterDisabled = currentCfgStr.indexOf("\n#!!!filterHostsFile =")!=-1;
	if (filterDisabled)
		currentCfgStr = currentCfgStr.replace("\n#!!!filterHostsFile =", "\nfilterHostsFile =");
	Properties currentConfig = new Properties();
	currentConfig.load(new ByteArrayInputStream(currentCfgStr.getBytes()));

	String[] currentKeys = currentConfig.keySet().toArray(new String[0]);
	BufferedReader defCfgReader = new BufferedReader(new InputStreamReader(ExecutionEnvironment.getEnvironment().getAsset("dnsfilter.conf")));
	File mergedConfig = new File(WORKDIR+"dnsfilter.conf");
	FileOutputStream mergedout = new FileOutputStream(mergedConfig);
	String ln = "";

	//hostfile-net discontinued - take over new default filters in case currently defaults are set
	boolean useNewDefaultFilters = currentConfig.getProperty("previousAutoUpdateURL","").trim().equals("https://adaway.org/hosts.txt; https://hosts-file.net/ad_servers.txt; https://hosts-file.net/emd.txt");

	while ((ln = defCfgReader.readLine()) != null) {
		if (!(useNewDefaultFilters && ln.startsWith("filterAutoUpdateURL"))) {
			for (int i = 0; i < currentKeys.length; i++) {
				if (ln.startsWith(currentKeys[i] + " =")) {
					if (currentKeys[i].equals("filterHostsFile") && filterDisabled)
						ln = "#!!!filterHostsFile" + " = " + currentConfig.getProperty(currentKeys[i], "");
					else
						ln = currentKeys[i] + " = " + currentConfig.getProperty(currentKeys[i], "");
				}
			}
		} else Logger.getLogger().logLine("Taking over default configuration: "+ln);

		mergedout.write((ln + "\r\n").getBytes());
	}
	defCfgReader.close();

	//take over custom properties (such as filter overrules) which are not in def config
	Properties defProps = new Properties();
	defProps.load(ExecutionEnvironment.getEnvironment().getAsset("dnsfilter.conf"));
	boolean first = true;
	for (int i = 0; i < currentKeys.length; i++) {
		if (!defProps.containsKey(currentKeys[i])) {
			if (first)
				mergedout.write(("\r\n# Merged custom config from previous config file:\r\n").getBytes());
			first = false;
			ln = currentKeys[i] + " = " + currentConfig.getProperty(currentKeys[i], "");
			mergedout.write((ln + "\r\n").getBytes());
		}
	}
	mergedout.flush();
	mergedout.close();
	Logger.getLogger().logLine("Merged configuration 'dnsfilter.conf' after update to version " + DNSFilterManager.VERSION + "!");
	InputStream in = new FileInputStream(mergedConfig);
	byte[] configBytes = Utils.readFully(in, 1024);
	in.close();

	return configBytes;
}