java.io.BufferedReader

Here are the examples of the java api class java.io.BufferedReader taken from open source projects.

1. BufferedReaderTest#leavesMark()

Project: teavm
Source File: BufferedReaderTest.java
View license
@Test
public void leavesMark() throws IOException {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 1000; ++i) {
        sb.append((char) i);
    }
    BufferedReader reader = new BufferedReader(new StringReader(sb.toString()), 100);
    reader.skip(50);
    reader.mark(70);
    reader.skip(60);
    reader.reset();
    char[] buffer = new char[150];
    int charsRead = reader.read(buffer);
    assertEquals(150, charsRead);
    assertEquals(50, buffer[0]);
    assertEquals(51, buffer[1]);
    assertEquals(199, buffer[149]);
}

2. MiscUtils#printProcess()

Project: bytecode-viewer
Source File: MiscUtils.java
View license
public static void printProcess(Process process) throws Exception {
    //Read out dir output
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    br.close();
    is = process.getErrorStream();
    isr = new InputStreamReader(is);
    br = new BufferedReader(isr);
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    br.close();
}

3. IT#run()

Project: Duke
Source File: IT.java
View license
private Result run(String cmd) throws IOException {
    Process p = Runtime.getRuntime().exec(cmd);
    StringBuilder tmp = new StringBuilder();
    BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = r.readLine()) != null) tmp.append(line + " ");
    r.close();
    r = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    while ((line = r.readLine()) != null) tmp.append(line + " ");
    r.close();
    try {
        // we wait for process to exit
        p.waitFor();
    } catch (InterruptedException e) {
    }
    return new Result(tmp.toString(), p.exitValue());
}

4. GZIPcompress#main()

View license
public static void main(String[] args) throws IOException {
    // ?Reader???
    BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("data.gz"), "UTF-8"));
    // ???????????????
    BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream("data.gz")));
    System.out.println("Writing File ??");
    int c;
    while ((c = in.read()) > 0) out.write(String.valueOf((char) c).getBytes("UTF-8"));
    in.close();
    out.close();
    System.out.println("Reading File ??");
    // ??????????
    BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("data.gz")), // encoding question
    "UTF-8"));
    String s;
    while ((s = in2.readLine()) != null) System.out.println(s);
    in2.close();
}

5. ITDoggedCubeBuilderTest#fileCompare()

Project: kylin
Source File: ITDoggedCubeBuilderTest.java
View license
private void fileCompare(File file, File file2) throws IOException {
    BufferedReader r1 = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
    BufferedReader r2 = new BufferedReader(new InputStreamReader(new FileInputStream(file2), "UTF-8"));
    String line1, line2;
    do {
        line1 = r1.readLine();
        line2 = r2.readLine();
        assertEquals(line1, line2);
    } while (line1 != null || line2 != null);
    r1.close();
    r2.close();
}

6. TestInputOutputFormat#testReadWrite()

View license
private void testReadWrite(CompressionCodecName codec, Map<String, String> conf) throws IOException, ClassNotFoundException, InterruptedException {
    runMapReduceJob(codec, conf);
    final BufferedReader in = new BufferedReader(new FileReader(new File(inputPath.toString())));
    final BufferedReader out = new BufferedReader(new FileReader(new File(outputPath.toString(), "part-m-00000")));
    String lineIn;
    String lineOut = null;
    int lineNumber = 0;
    while ((lineIn = in.readLine()) != null && (lineOut = out.readLine()) != null) {
        ++lineNumber;
        lineOut = lineOut.substring(lineOut.indexOf("\t") + 1);
        assertEquals("line " + lineNumber, lineIn, lineOut);
    }
    assertNull("line " + lineNumber, out.readLine());
    assertNull("line " + lineNumber, lineIn);
    in.close();
    out.close();
}

7. AbstractPacketTest#testToString()

Project: pcap4j
Source File: AbstractPacketTest.java
View license
@Test
public void testToString() throws Exception {
    FileReader fr = new FileReader(new StringBuilder().append(resourceDirPath).append("/").append(getClass().getSimpleName()).append(".log").toString());
    BufferedReader fbr = new BufferedReader(fr);
    StringReader sr = new StringReader(getPacket().toString());
    BufferedReader sbr = new BufferedReader(sr);
    String line;
    while ((line = fbr.readLine()) != null) {
        assertEquals(line, sbr.readLine());
    }
    assertNull(sbr.readLine());
    fbr.close();
    fr.close();
    sr.close();
    sbr.close();
}

8. TestParamSubPreproc#compareResults()

Project: pig
Source File: TestParamSubPreproc.java
View license
private void compareResults(InputStream expected, InputStream result) throws IOException {
    BufferedReader inExpected = new BufferedReader(new InputStreamReader(expected));
    BufferedReader inResult = new BufferedReader(new InputStreamReader(result));
    String exLine;
    String resLine;
    int lineNum = 0;
    while (true) {
        lineNum++;
        exLine = inExpected.readLine();
        resLine = inResult.readLine();
        if (exLine == null || resLine == null)
            break;
        assertEquals("Command line parameter substitution failed. " + "Expected : " + exLine + " , but got : " + resLine + " in line num : " + lineNum, exLine.trim(), resLine.trim());
    }
    if (!(exLine == null && resLine == null)) {
        fail("Command line parameter substitution failed. " + "Expected : " + exLine + " , but got : " + resLine + " in line num : " + lineNum);
    }
    inExpected.close();
    inResult.close();
}

9. echo#echoTCP()

Project: commons-net
Source File: echo.java
View license
public static final void echoTCP(String host) throws IOException {
    EchoTCPClient client = new EchoTCPClient();
    BufferedReader input, echoInput;
    PrintWriter echoOutput;
    String line;
    // We want to timeout if a response takes longer than 60 seconds
    client.setDefaultTimeout(60000);
    client.connect(host);
    System.out.println("Connected to " + host + ".");
    input = new BufferedReader(new InputStreamReader(System.in));
    echoOutput = new PrintWriter(new OutputStreamWriter(client.getOutputStream()), true);
    echoInput = new BufferedReader(new InputStreamReader(client.getInputStream()));
    while ((line = input.readLine()) != null) {
        echoOutput.println(line);
        System.out.println(echoInput.readLine());
    }
    client.disconnect();
}

10. SeqEval#readOOV()

Project: fnlp
Source File: SeqEval.java
View license
public HashSet<String> readOOV(String path) throws IOException {
    dict = new HashSet<String>();
    BufferedReader bfr;
    bfr = new BufferedReader(new InputStreamReader(new FileInputStream(path), "utf8"));
    String line = null;
    while ((line = bfr.readLine()) != null) {
        if (line.length() == 0)
            continue;
        dict.add(line);
    }
    bfr.close();
    return dict;
}

11. WordGraph#read()

Project: fnlp
Source File: WordGraph.java
View license
public void read(String path) throws IOException {
    BufferedReader bfr;
    bfr = new BufferedReader(new InputStreamReader(new FileInputStream(path), "utf8"));
    String line = null;
    while ((line = bfr.readLine()) != null) {
        if (line.length() == 0)
            continue;
        String[] toks = line.split("\\s+");
        WordRelationEnum rel = WordRelationEnum.getWithName(toks[0]);
        if (toks.length < 2)
            continue;
        addRel(rel, Arrays.copyOfRange(toks, 1, toks.length));
    }
    bfr.close();
}

12. TextFile#readAllLines()

Project: hapi-fhir
Source File: TextFile.java
View license
public static List<String> readAllLines(String path) throws IOException {
    List<String> result = new ArrayList<String>();
    File file = new CSFile(path);
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
    while (reader.ready()) result.add(reader.readLine());
    reader.close();
    return result;
}

13. ExternalSortTest#testMergeSortedFiles()

View license
@Test
public void testMergeSortedFiles() throws Exception {
    String line;
    List<String> result;
    BufferedReader bf;
    Comparator<String> cmp = new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    };
    File out = folder.newFile();
    ExternalSort.mergeSortedFiles(this.fileList, out, cmp, Charset.defaultCharset(), false);
    bf = new BufferedReader(new FileReader(out));
    result = new ArrayList<String>();
    while ((line = bf.readLine()) != null) {
        result.add(line);
    }
    bf.close();
    assertArrayEquals(Arrays.toString(result.toArray()), EXPECTED_MERGE_RESULTS, result.toArray());
}

14. ExternalSortTest#testMergeSortedFilesDistinct()

View license
@Test
public void testMergeSortedFilesDistinct() throws Exception {
    String line;
    List<String> result;
    BufferedReader bf;
    Comparator<String> cmp = new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    };
    File out = folder.newFile();
    ExternalSort.mergeSortedFiles(this.fileList, out, cmp, Charset.defaultCharset(), true);
    bf = new BufferedReader(new FileReader(out));
    result = new ArrayList<String>();
    while ((line = bf.readLine()) != null) {
        result.add(line);
    }
    bf.close();
    assertArrayEquals(Arrays.toString(result.toArray()), EXPECTED_MERGE_DISTINCT_RESULTS, result.toArray());
}

15. HttpNegotiateServer#test6578647()

Project: jdk7u-jdk
Source File: HttpNegotiateServer.java
View license
static void test6578647() throws Exception {
    BufferedReader reader;
    java.net.Authenticator.setDefault(new KnowAllAuthenticator());
    reader = new BufferedReader(new InputStreamReader(webUrl.openConnection().getInputStream()));
    if (!reader.readLine().equals(CONTENT)) {
        throw new RuntimeException("Bad content");
    }
    reader = new BufferedReader(new InputStreamReader(proxyUrl.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, proxyPort))).getInputStream()));
    if (!reader.readLine().equals(CONTENT)) {
        throw new RuntimeException("Bad content");
    }
}

16. ReTokenizeFile#readFile()

Project: lenya
Source File: ReTokenizeFile.java
View license
/**
     * reads a file in the specified encoding.
     * @param file the file to read.
     * @param encoding the file encoding
     * @return the content of the file.
     * @throws FileNotFoundException if the file does not exists.
     * @throws IOException if something else went wrong.
     */
protected String readFile(File file, Charset charset) throws FileNotFoundException, IOException {
    FileInputStream inputFile = new FileInputStream(file);
    InputStreamReader inputStream;
    if (charset != null) {
        inputStream = new InputStreamReader(inputFile, charset);
    } else {
        inputStream = new InputStreamReader(inputFile);
    }
    BufferedReader bufferReader = new BufferedReader(inputStream);
    StringBuffer buffer = new StringBuffer();
    String line = "";
    while (bufferReader.ready()) {
        line = bufferReader.readLine();
        buffer.append(line);
    }
    bufferReader.close();
    inputStream.close();
    inputFile.close();
    return buffer.toString();
}

17. HttpNegotiateServer#test6578647()

Project: openjdk
Source File: HttpNegotiateServer.java
View license
static void test6578647() throws Exception {
    BufferedReader reader;
    java.net.Authenticator.setDefault(new KnowAllAuthenticator());
    reader = new BufferedReader(new InputStreamReader(webUrl.openConnection().getInputStream()));
    if (!reader.readLine().equals(CONTENT)) {
        throw new RuntimeException("Bad content");
    }
    reader = new BufferedReader(new InputStreamReader(proxyUrl.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, proxyPort))).getInputStream()));
    if (!reader.readLine().equals(CONTENT)) {
        throw new RuntimeException("Bad content");
    }
}

18. AuditManager#getReviewInfo()

Project: spacewalk
Source File: AuditManager.java
View license
/**
     * Retrieve the review info for a specified machine/time
     * @param machine The machine name
     * @param start The start time in ms from the epoch
     * @param end The end time in ms from the epoch
     * @throws IOException Throws when the audit review file is unreadable
     * @return An AuditReviewDto, possibly with review info set
     */
public static AuditReviewDto getReviewInfo(String machine, long start, long end) throws IOException {
    BufferedReader brdr;
    Date reviewedOn = null;
    String str, part1, reviewedBy = null;
    String[] revInfo;
    part1 = machine + "," + (start / 1000) + "," + (end / 1000) + ",";
    brdr = new BufferedReader(new FileReader(reviewFile));
    while ((str = brdr.readLine()) != null) {
        if (str.startsWith(part1)) {
            revInfo = str.split(",");
            reviewedBy = revInfo[3];
            reviewedOn = new Date(Long.parseLong(revInfo[4]) * 1000);
            break;
        }
    }
    brdr.close();
    return new AuditReviewDto(machine, new Date(start), new Date(end), reviewedBy, reviewedOn);
}

19. GraphBuilder_Popularity#readObjectProperties()

View license
private List<Triple> readObjectProperties(String objectPropertiesFile) throws IOException {
    InputStream f;
    BufferedReader br;
    String line;
    String[] parts;
    List<Triple> triples = new ArrayList<Triple>();
    f = new FileInputStream(objectPropertiesFile);
    br = new BufferedReader(new InputStreamReader(f, Charset.forName("UTF-8")));
    while ((line = br.readLine()) != null) {
        parts = line.trim().split(",");
        if (parts == null || parts.length != 4)
            continue;
        Triple t = new Triple(parts[0].trim(), parts[1].trim(), parts[2].trim(), Integer.parseInt(parts[3].trim()));
        triples.add(t);
    }
    // Done with the file
    br.close();
    br = null;
    f = null;
    return triples;
}

20. GraphBuilder_Popularity#readDataProperties()

View license
private List<Triple> readDataProperties(String dataPropertiesFile) throws IOException {
    InputStream f;
    BufferedReader br;
    String line;
    String[] parts;
    List<Triple> triples = new ArrayList<Triple>();
    f = new FileInputStream(dataPropertiesFile);
    br = new BufferedReader(new InputStreamReader(f, Charset.forName("UTF-8")));
    while ((line = br.readLine()) != null) {
        parts = line.trim().split(",");
        if (parts == null || parts.length != 3)
            continue;
        Triple t = new Triple(parts[0].trim(), parts[1].trim(), Integer.parseInt(parts[2].trim()));
        triples.add(t);
    }
    // Done with the file
    br.close();
    br = null;
    f = null;
    return triples;
}

21. FCMTopicManager#get()

View license
/**
     * Sends GET HTTP request to provided URL. Request is authorized using Google API key.
     *
     * @param urlS target URL string
     */
private String get(String urlS) throws IOException {
    URL url = new URL(urlS);
    HttpURLConnection conn = prepareAuthorizedConnection(url);
    conn.setRequestMethod("GET");
    // Read response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder result = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    rd.close();
    return result.toString();
}

22. DebugLogs#runProcess()

View license
/**
     * Run a shell command and return the results
     *
     * @param command
     * @return
     * @throws IOException
     */
private String runProcess(String[] command) throws IOException {
    Process process = null;
    if (command.length == 1) {
        process = Runtime.getRuntime().exec(command[0]);
    } else {
        Runtime.getRuntime().exec(command);
    }
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    StringBuilder log = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        log.append(line);
        log.append("\n");
    }
    bufferedReader.close();
    return log.toString();
}

23. FileUtil#streamToString()

View license
public static String streamToString(InputStream input) throws IOException {
    InputStreamReader isr = new InputStreamReader(input);
    BufferedReader reader = new BufferedReader(isr);
    String line;
    StringBuffer sb = new StringBuffer();
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    reader.close();
    isr.close();
    return sb.toString();
}

24. PluginWebViewActivity#streamToString()

View license
private static String streamToString(InputStream input) throws IOException {
    InputStreamReader isr = new InputStreamReader(input);
    BufferedReader reader = new BufferedReader(isr);
    String line;
    StringBuffer sb = new StringBuffer();
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    reader.close();
    isr.close();
    return sb.toString();
}

25. IOUtils#contentEqualsIgnoreEOL()

Project: Android-RTEditor
Source File: IOUtils.java
View license
/**
     * Compare the contents of two Readers to determine if they are equal or
     * not, ignoring EOL characters.
     * <p/>
     * This method buffers the input internally using
     * <code>BufferedReader</code> if they are not already buffered.
     *
     * @param input1 the first reader
     * @param input2 the second reader
     * @return true if the content of the readers are equal (ignoring EOL differences),  false otherwise
     * @throws NullPointerException if either input is null
     * @throws IOException          if an I/O error occurs
     * @since 2.2
     */
public static boolean contentEqualsIgnoreEOL(Reader input1, Reader input2) throws IOException {
    BufferedReader br1 = toBufferedReader(input1);
    BufferedReader br2 = toBufferedReader(input2);
    String line1 = br1.readLine();
    String line2 = br2.readLine();
    while (line1 != null && line2 != null && line1.equals(line2)) {
        line1 = br1.readLine();
        line2 = br2.readLine();
    }
    return line1 == null ? line2 == null ? true : false : line1.equals(line2);
}

26. Utils#replaceText()

Project: ATLauncher
Source File: Utils.java
View license
/**
     * Replace text.
     *
     * @param originalFile    the original file
     * @param destinationFile the destination file
     * @param replaceThis     the replace this
     * @param withThis        the with this
     * @throws IOException Signals that an I/O exception has occurred.
     */
public static void replaceText(File originalFile, File destinationFile, String replaceThis, String withThis) throws IOException {
    FileInputStream fs = new FileInputStream(originalFile);
    BufferedReader br = new BufferedReader(new InputStreamReader(fs));
    FileWriter writer1 = new FileWriter(destinationFile);
    String line = br.readLine();
    while (line != null) {
        if (line.contains(replaceThis)) {
            line = line.replace(replaceThis, withThis);
        }
        writer1.write(line);
        writer1.write(System.getProperty("line.separator"));
        line = br.readLine();
    }
    writer1.flush();
    writer1.close();
    br.close();
    fs.close();
}

27. JSONIntegrationTest#testPOJOServiceWithJSONBadgerfish()

Project: axis2-java
Source File: JSONIntegrationTest.java
View license
@Test
public void testPOJOServiceWithJSONBadgerfish() throws Exception {
    HttpURLConnection conn = (HttpURLConnection) new URL(server.getEndpoint("POJOService")).openConnection();
    conn.setDoOutput(true);
    conn.addRequestProperty("Content-Type", "application/json/badgerfish");
    Writer out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
    // XML is: <sayHello xmlns="http://example.org"><myName>Joe</myName></sayHello>
    out.write("{ \"sayHello\" : { \"@xmlns\" : { \"$\" : \"http://example.org\" }, \"myName\" : { \"$\" : \"Joe\" } } }");
    out.close();
    assertEquals(200, conn.getResponseCode());
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    assertTrue(in.readLine().contains("Hello Joe!"));
    in.close();
}

28. JSONIntegrationTest#testPOJOServiceWithJSONMapped()

Project: axis2-java
Source File: JSONIntegrationTest.java
View license
@Test
public void testPOJOServiceWithJSONMapped() throws Exception {
    HttpURLConnection conn = (HttpURLConnection) new URL(server.getEndpoint("POJOService")).openConnection();
    conn.setDoOutput(true);
    conn.addRequestProperty("Content-Type", "application/json");
    Writer out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
    out.write("{ \"sayHello\" : { \"myName\" : \"Joe\" } }");
    out.close();
    assertEquals(200, conn.getResponseCode());
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    assertEquals("{\"sayHelloResponse\":{\"return\":\"Hello Joe!\"}}", in.readLine());
    in.close();
}

29. Configuration#read()

Project: barefoot
Source File: Configuration.java
View license
/**
     * Reads road type configuration from file.
     *
     * @param path Path of the road type configuration file.
     * @return Mapping of road class identifiers to priority factor and default maximum speed.
     * @throws JSONException thrown on JSON extraction or parsing error.
     * @throws IOException thrown on file reading error.
     */
public static Map<Short, Tuple<Double, Integer>> read(String path) throws JSONException, IOException {
    BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
    String line = null, json = new String();
    while ((line = file.readLine()) != null) {
        json += line;
    }
    file.close();
    return read(new JSONObject(json));
}

30. SHA3DigestTest#testVectors()

Project: bc-java
Source File: SHA3DigestTest.java
View license
public void testVectors() throws Exception {
    BufferedReader r = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("SHA3TestVectors.txt")));
    String line;
    while (null != (line = readLine(r))) {
        if (line.length() != 0) {
            TestVector v = readTestVector(r, line);
            runTestVector(v);
        }
    }
    r.close();
}

31. SHAKEDigestTest#testVectors()

Project: bc-java
Source File: SHAKEDigestTest.java
View license
public void testVectors() throws Exception {
    BufferedReader r = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("SHAKETestVectors.txt")));
    String line;
    while (null != (line = readLine(r))) {
        if (line.length() != 0) {
            TestVector v = readTestVector(r, line);
            runTestVector(v);
        }
    }
    r.close();
}

32. AlignmentToolsTest#testUpdateSuperposition()

Project: biojava
Source File: AlignmentToolsTest.java
View license
/**
	 * Tests that {@link AlignmentTools#updateSuperposition(AFPChain, Atom[], Atom[])} calculates the correct RMSD and TM-score for an AFPChain of 1 block.
	 * TODO: Write a test with 2 blocks
	 */
public void testUpdateSuperposition() throws IOException, StructureException {
    Structure s = StructureTools.getStructure("31BI");
    Atom[] ca1 = StructureTools.getRepresentativeAtomArray(s);
    Atom[] ca2 = StructureTools.getRepresentativeAtomArray(s);
    StringBuilder sb = new StringBuilder();
    BufferedReader br = new BufferedReader(new FileReader("src/test/resources/align/31BI_symm_align.xml"));
    String line = "";
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    br.close();
    AFPChain afpChain = AFPChainXMLParser.fromXML(sb.toString(), ca1, ca2);
    afpChain.setTMScore(-1);
    afpChain.setTotalRmsdOpt(-1);
    AlignmentTools.updateSuperposition(afpChain, ca1, ca2);
    assertEquals("TM-score is wrong", 0.62779, afpChain.getTMScore(), 0.001);
    assertEquals("RMSD is wrong", 2.50569, afpChain.getTotalRmsdOpt(), 0.001);
}

33. PDBFileParser#getBufferedReader()

Project: biojava
Source File: PDBFileParser.java
View license
private BufferedReader getBufferedReader(InputStream inStream) throws IOException {
    BufferedReader buf;
    if (inStream == null) {
        throw new IOException("input stream is null!");
    }
    buf = new BufferedReader(new InputStreamReader(inStream));
    return buf;
}

34. TestMultipleAlignmentWriter#testFASTA1()

View license
@Test
public void testFASTA1() throws IOException {
    String result = MultipleAlignmentWriter.toFASTA(alignment1);
    FileReader file = new FileReader("src/test/resources/testMSTA1.fasta");
    BufferedReader reader = new BufferedReader(file);
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
        stringBuilder.append("\n");
    }
    reader.close();
    String expected = stringBuilder.toString();
    assertEquals(expected, result);
}

35. TestMultipleAlignmentWriter#testFASTA2()

View license
@Test
public void testFASTA2() throws IOException {
    String result = MultipleAlignmentWriter.toFASTA(alignment2);
    FileReader file = new FileReader("src/test/resources/testMSTA2.fasta");
    BufferedReader reader = new BufferedReader(file);
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
        stringBuilder.append("\n");
    }
    reader.close();
    String expected = stringBuilder.toString();
    assertEquals(expected, result);
}

36. TestMultipleAlignmentWriter#testFatCat1()

View license
@Test
public void testFatCat1() throws IOException {
    String result = MultipleAlignmentWriter.toFatCat(alignment1);
    FileReader file = new FileReader("src/test/resources/testMSTA1.fatcat");
    BufferedReader reader = new BufferedReader(file);
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
        stringBuilder.append("\n");
    }
    reader.close();
    String expected = stringBuilder.toString();
    assertEquals(expected, result);
}

37. TestMultipleAlignmentWriter#testFatCat2()

View license
@Test
public void testFatCat2() throws IOException {
    String result = MultipleAlignmentWriter.toFatCat(alignment2);
    FileReader file = new FileReader("src/test/resources/testMSTA2.fatcat");
    BufferedReader reader = new BufferedReader(file);
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
        stringBuilder.append("\n");
    }
    reader.close();
    String expected = stringBuilder.toString();
    assertEquals(expected, result);
}

38. TestMultipleAlignmentWriter#testAlignedResidues1()

View license
@Test
public void testAlignedResidues1() throws IOException {
    String result = MultipleAlignmentWriter.toAlignedResidues(alignment1);
    FileReader file = new FileReader("src/test/resources/testMSTA1_alnres.tsv");
    BufferedReader reader = new BufferedReader(file);
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
        stringBuilder.append("\n");
    }
    reader.close();
    String expected = stringBuilder.toString();
    assertEquals(expected, result);
}

39. TestMultipleAlignmentWriter#testAlignedResidues2()

View license
@Test
public void testAlignedResidues2() throws IOException {
    String result = MultipleAlignmentWriter.toAlignedResidues(alignment2);
    FileReader file = new FileReader("src/test/resources/testMSTA2_alnres.tsv");
    BufferedReader reader = new BufferedReader(file);
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
        stringBuilder.append("\n");
    }
    reader.close();
    String expected = stringBuilder.toString();
    assertEquals(expected, result);
}

40. TestMultipleAlignmentWriter#testTransformMatrices1()

View license
@Test
public void testTransformMatrices1() throws IOException {
    String result = MultipleAlignmentWriter.toTransformMatrices(alignment1);
    FileReader file = new FileReader("src/test/resources/testMSTA1.transforms");
    BufferedReader reader = new BufferedReader(file);
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
        stringBuilder.append("\n");
    }
    reader.close();
    String expected = stringBuilder.toString();
    assertEquals(expected, result);
}

41. TestMultipleAlignmentWriter#testTransformMatrices2()

View license
@Test
public void testTransformMatrices2() throws IOException {
    String result = MultipleAlignmentWriter.toTransformMatrices(alignment2);
    System.out.println(result);
    FileReader file = new FileReader("src/test/resources/testMSTA2.transforms");
    BufferedReader reader = new BufferedReader(file);
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
        stringBuilder.append("\n");
    }
    reader.close();
    String expected = stringBuilder.toString();
// TODO THIS SHOULD BE REWRITTEN TO USE FLOATS
//assertEquals(expected,result);
}

42. TestMultipleAlignmentWriter#testXMLformat1()

View license
@Test
public void testXMLformat1() throws IOException {
    MultipleAlignmentEnsemble ensemble = alignment1.getEnsemble();
    String result = MultipleAlignmentWriter.toXML(ensemble);
    FileReader file = new FileReader("src/test/resources/testMSTA1.xml");
    BufferedReader reader = new BufferedReader(file);
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
        stringBuilder.append("\n");
    }
    reader.close();
    String expected = stringBuilder.toString();
    assertEquals(expected, result);
}

43. TestMultipleAlignmentWriter#testXMLformat2()

View license
@Test
public void testXMLformat2() throws IOException {
    MultipleAlignmentEnsemble ensemble = alignment2.getEnsemble();
    String result = MultipleAlignmentWriter.toXML(ensemble);
    FileReader file = new FileReader("src/test/resources/testMSTA2.xml");
    BufferedReader reader = new BufferedReader(file);
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
        stringBuilder.append("\n");
    }
    reader.close();
    String expected = stringBuilder.toString();
// TODO THIS SHOULD BE REWRITTEN TO DO FLOAT AND NOT TEXT COMPARISON
//		assertEquals(expected,result);
}

44. ExtractTrainingData#readCategoryFile()

Project: book
Source File: ExtractTrainingData.java
View license
/** Read the category file from disk, see {@link #extractTraininingData(File, File, Collection, Collection, File)}
   *  for a description of the format.
   * 
   * @param categoryFile
   * @return
   * @throws IOException
   */
public static Map<String, List<String>> readCategoryFile(File categoryFile) throws IOException {
    Map<String, List<String>> categoryMap = new HashMap<String, List<String>>();
    BufferedReader rin = new BufferedReader(new InputStreamReader(new FileInputStream(categoryFile), "UTF-8"));
    String line;
    while ((line = rin.readLine()) != null) {
        String[] parts = line.trim().toLowerCase().split("\\s+");
        if (parts.length > 0) {
            String key = parts[0];
            for (String e : parts) {
                List<String> entries = categoryMap.get(key);
                if (entries == null) {
                    entries = new LinkedList<String>();
                    categoryMap.put(key, entries);
                }
                entries.add(e);
            }
        }
    }
    rin.close();
    return categoryMap;
}

45. TrieNode#main()

Project: book
Source File: TrieNode.java
View license
public static void main(String[] args) throws IOException {
    TrieNode node = new TrieNode(false);
    int lc = 0;
    BufferedReader br = new BufferedReader(new FileReader(args[0]));
    for (String line = br.readLine(); line != null; line = br.readLine()) {
        node.addWord(line);
        lc++;
    }
    System.out.println("Loaded " + lc + " lines");
    BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
    for (String line = br2.readLine(); line != null; line = br2.readLine()) {
        String[] words = node.getWords(line, 10);
        System.out.println(java.util.Arrays.asList(words));
    }
}

46. SiteMapGeneratorTest#convertFileToString()

View license
protected String convertFileToString(File file) throws IOException {
    FileInputStream fin = new FileInputStream(file);
    BufferedReader br = new BufferedReader(new InputStreamReader(fin));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        if (line.contains("</lastmod>")) {
            continue;
        }
        line = line.replaceAll("\\s+", "");
        sb.append(line);
    }
    br.close();
    fin.close();
    return sb.toString();
}

47. SiteMapGeneratorTest#convertFileToString()

View license
protected String convertFileToString(File file) throws IOException {
    FileInputStream fin = new FileInputStream(file);
    BufferedReader br = new BufferedReader(new InputStreamReader(fin));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        if (line.contains("</lastmod>")) {
            continue;
        }
        line = line.replaceAll("\\s+", "");
        sb.append(line);
    }
    br.close();
    fin.close();
    return sb.toString();
}

48. HtmlFetcher#main()

Project: browser-android
Source File: HtmlFetcher.java
View license
public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new FileReader("urls.txt"));
    String line = null;
    Set<String> existing = new LinkedHashSet<String>();
    while ((line = reader.readLine()) != null) {
        int index1 = line.indexOf("\"");
        int index2 = line.indexOf("\"", index1 + 1);
        String url = line.substring(index1 + 1, index2);
        String domainStr = SHelper.extractDomain(url, true);
        String counterStr = "";
        // TODO more similarities
        if (existing.contains(domainStr))
            counterStr = "2";
        else
            existing.add(domainStr);
        String html = new HtmlFetcher().fetchAsString(url, 20000);
        String outFile = domainStr + counterStr + ".html";
        BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
        writer.write(html);
        writer.close();
    }
    reader.close();
}

49. Activator#rankingOfUniqueNameProperties()

Project: btm
Source File: Activator.java
View license
private Map<String, Integer> rankingOfUniqueNameProperties(File file) throws FileNotFoundException, IOException {
    Map<String, Integer> lineNumbers = new HashMap<String, Integer>();
    BufferedReader reader = new BufferedReader(new FileReader(file));
    int ranking = 1;
    for (String line = reader.readLine(); line != null; line = reader.readLine()) {
        Matcher matcher = UNIQUE_NAME.matcher(line);
        if (matcher.matches()) {
            lineNumbers.put(matcher.group(1), ranking);
            ranking++;
        }
    }
    reader.close();
    return lineNumbers;
}

50. FileURLDecodingTest#assertTargetFile()

Project: camel
Source File: FileURLDecodingTest.java
View license
private void assertTargetFile(final String encoded, final String expected) throws Exception {
    context.addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("direct:start").to("file:" + TARGET_DIR + "?fileName=" + encoded);
        }
    });
    context.start();
    String result = template.requestBody("direct:start", "Kermit", String.class);
    assertEquals("Kermit", result);
    BufferedReader br = new BufferedReader(new FileReader(Paths.get(TARGET_DIR, expected).toFile()));
    assertEquals("Kermit", br.readLine());
    br.close();
}

51. IOConverterCharsetTest#testToInputStreamFileWithCharsetUTF8()

Project: camel
Source File: IOConverterCharsetTest.java
View license
public void testToInputStreamFileWithCharsetUTF8() throws Exception {
    switchToDefaultCharset("UTF-8");
    File file = new File("src/test/resources/org/apache/camel/converter/german.utf-8.txt");
    InputStream in = IOConverter.toInputStream(file, "UTF-8");
    // do read with default charset!
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    BufferedReader naiveReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
    try {
        String line = reader.readLine();
        String naiveLine = naiveReader.readLine();
        assertEquals(naiveLine, line);
        assertEquals(CONTENT, line);
    } finally {
        reader.close();
        naiveReader.close();
    }
}

52. IOConverterCharsetTest#testToInputStreamFileWithCharsetUTF8withOtherDefaultEncoding()

Project: camel
Source File: IOConverterCharsetTest.java
View license
public void testToInputStreamFileWithCharsetUTF8withOtherDefaultEncoding() throws Exception {
    switchToDefaultCharset("ISO-8859-1");
    File file = new File("src/test/resources/org/apache/camel/converter/german.utf-8.txt");
    InputStream in = IOConverter.toInputStream(file, "UTF-8");
    // do read with default charset!
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    BufferedReader naiveReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
    try {
        String line = reader.readLine();
        String naiveLine = naiveReader.readLine();
        assertEquals(naiveLine, line);
        assertEquals(CONTENT, line);
    } finally {
        reader.close();
        naiveReader.close();
    }
}

53. IOConverterCharsetTest#testToInputStreamFileWithCharsetLatin1()

Project: camel
Source File: IOConverterCharsetTest.java
View license
public void testToInputStreamFileWithCharsetLatin1() throws Exception {
    switchToDefaultCharset("UTF-8");
    File file = new File("src/test/resources/org/apache/camel/converter/german.iso-8859-1.txt");
    InputStream in = IOConverter.toInputStream(file, "ISO-8859-1");
    // do read with default charset!
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    BufferedReader naiveReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "ISO-8859-1"));
    try {
        String line = reader.readLine();
        String naiveLine = naiveReader.readLine();
        assertEquals(naiveLine, line);
        assertEquals(CONTENT, line);
    } finally {
        reader.close();
        naiveReader.close();
    }
}

54. IOConverterCharsetTest#testToReaderFileWithCharsetUTF8()

Project: camel
Source File: IOConverterCharsetTest.java
View license
public void testToReaderFileWithCharsetUTF8() throws Exception {
    File file = new File("src/test/resources/org/apache/camel/converter/german.utf-8.txt");
    BufferedReader reader = IOConverter.toReader(file, "UTF-8");
    BufferedReader naiveReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
    try {
        String line = reader.readLine();
        String naiveLine = naiveReader.readLine();
        assertEquals(naiveLine, line);
        assertEquals(CONTENT, line);
    } finally {
        reader.close();
        naiveReader.close();
    }
}

55. IOConverterCharsetTest#testToReaderFileWithCharsetLatin1()

Project: camel
Source File: IOConverterCharsetTest.java
View license
public void testToReaderFileWithCharsetLatin1() throws Exception {
    File file = new File("src/test/resources/org/apache/camel/converter/german.iso-8859-1.txt");
    BufferedReader reader = IOConverter.toReader(file, "ISO-8859-1");
    BufferedReader naiveReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "ISO-8859-1"));
    try {
        String line = reader.readLine();
        String naiveLine = naiveReader.readLine();
        assertEquals(naiveLine, line);
        assertEquals(CONTENT, line);
    } finally {
        reader.close();
        naiveReader.close();
    }
}

56. HttpRoundtripHeaderTest#readLastLine()

Project: camel
Source File: HttpRoundtripHeaderTest.java
View license
private String readLastLine(InputStream answer) throws IOException {
    String lastLine = null;
    BufferedReader reader = IOHelper.buffered(new InputStreamReader(answer));
    while (true) {
        String line = reader.readLine();
        if (line == null) {
            break;
        }
        lastLine = line;
        log.info("Read: " + line);
    }
    reader.close();
    return lastLine;
}

57. Compare#compare()

Project: chainsaw
Source File: Compare.java
View license
public static boolean compare(Class testClass, final String file1, final String file2) throws IOException {
    BufferedReader in1 = new BufferedReader(new FileReader(file1));
    BufferedReader in2 = new BufferedReader(new InputStreamReader(open(testClass, file2)));
    try {
        return compare(testClass, file1, file2, in1, in2);
    } finally {
        in1.close();
        in2.close();
    }
}

58. Compare#gzCompare()

Project: chainsaw
Source File: Compare.java
View license
public static boolean gzCompare(final Class testClass, final String actual, final String expected) throws FileNotFoundException, IOException {
    String resourceName = expected;
    int lastSlash = expected.lastIndexOf("/");
    if (lastSlash >= 0) {
        resourceName = expected.substring(lastSlash + 1);
    }
    InputStream resourceStream = testClass.getResourceAsStream(resourceName);
    if (resourceStream == null) {
        throw new FileNotFoundException("Could not locate resource " + resourceName);
    }
    BufferedReader in1 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(actual))));
    BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(resourceStream)));
    try {
        return gzCompare(testClass, actual, expected, in1, in2);
    } finally {
        in1.close();
        in2.close();
    }
}

59. ProcessUtil#process()

Project: che
Source File: ProcessUtil.java
View license
/**
     * Writes stdout and stderr of the process to consumers.<br>
     * Supposes that stderr of the process is redirected to stdout.
     *
     * @param p
     *         process to read output from
     * @param stdout
     *         a consumer where stdout will be redirected
     * @param stderr
     *         a consumer where stderr will be redirected
     * @throws IOException
     */
public static void process(Process p, LineConsumer stdout, LineConsumer stderr) throws IOException {
    try (BufferedReader inputReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()))) {
        String line;
        while ((line = inputReader.readLine()) != null) {
            stdout.writeLine(line);
        }
        while ((line = errorReader.readLine()) != null) {
            stderr.writeLine(line);
        }
    }
}

60. RefactoringHistoryManager#readRefactoringDescriptorProxies()

Project: che
Source File: RefactoringHistoryManager.java
View license
/**
	 * Reads refactoring descriptor proxies from the specified input stream.
	 * <p>
	 * The refactoring descriptor proxies are returned in no particular order.
	 * </p>
	 *
	 * @param stream
	 *            the input stream where to read from
	 * @param project
	 *            the name of the project, or <code>null</code> for the
	 *            workspace
	 * @param start
	 *            the start time stamp, inclusive
	 * @param end
	 *            the end time stamp, inclusive
	 * @return An array of refactoring descriptor proxies
	 * @throws IOException
	 *             if an input/output error occurs
	 */
public static RefactoringDescriptorProxy[] readRefactoringDescriptorProxies(final InputStream stream, final String project, final long start, final long end) throws IOException {
    final List list = new ArrayList();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(stream, IRefactoringSerializationConstants.OUTPUT_ENCODING));
    while (reader.ready()) {
        final String line = reader.readLine();
        if (line != null) {
            final int index = line.indexOf(DELIMITER_COMPONENT);
            if (index > 0) {
                try {
                    final long stamp = new Long(line.substring(0, index)).longValue();
                    if (stamp >= start && stamp <= end)
                        list.add(new DefaultRefactoringDescriptorProxy(unescapeString(line.substring(index + 1)), project, stamp));
                } catch (NumberFormatException exception) {
                }
            }
        }
    }
    return (RefactoringDescriptorProxy[]) list.toArray(new RefactoringDescriptorProxy[list.size()]);
}

61. FixEncoding#loadWithLocalEncoding()

Project: chipKIT32-MAX
Source File: FixEncoding.java
View license
protected String loadWithLocalEncoding(File file) throws IOException {
    // FileReader uses the default encoding, which is what we want.
    FileReader fr = new FileReader(file);
    BufferedReader reader = new BufferedReader(fr);
    StringBuffer buffer = new StringBuffer();
    String line = null;
    while ((line = reader.readLine()) != null) {
        buffer.append(line);
        buffer.append('\n');
    }
    reader.close();
    return buffer.toString();
}

62. FeatureCodeBuilder#main()

Project: CLAVIN
Source File: FeatureCodeBuilder.java
View license
/**
     * Reads-in featureCodes_en.txt file, spits-out
     * {@link FeatureClass} enum definitions.
     * @param args the command line arguments
     *
     * @throws FileNotFoundException if featureCodes_en.txt is not found on the classpath
     * @throws IOException if an error occurs reading the featureCodes file
     */
public static void main(String[] args) throws FileNotFoundException, IOException {
    InputStream codeStream = FeatureCodeBuilder.class.getClassLoader().getResourceAsStream("featureCodes_en.txt");
    BufferedReader in = new BufferedReader(new InputStreamReader(codeStream, Charset.forName("UTF-8")));
    // generate dummy feature code for top-level territories
    Set<Code> featureCodes = new TreeSet<Code>();
    featureCodes.add(new Code("TERRI", "A", "independent territory", "a territory that acts as an independent political entity", "manually added to identify territories that can contain other administrative divisions"));
    String line;
    while ((line = in.readLine()) != null) {
        String[] tokens = line.split("\t");
        if (!tokens[0].equals("null")) {
            String[] codes = tokens[0].split("\\.");
            featureCodes.add(new Code(codes[1], codes[0], tokens[1], tokens.length == 3 ? tokens[2] : ""));
        }
    }
    in.close();
    for (Code code : featureCodes) {
        System.out.println(code);
    }
    System.out.println("// manually added for locations not assigned to a feature code");
    System.out.println("NULL(FeatureClass.NULL, \"not available\", \"\", false);");
}

63. BasicGeoNameTest#testParseExceptions()

Project: CLAVIN
Source File: BasicGeoNameTest.java
View license
/**
     * Parse a "bad" gazetteer record to make sure exceptions are
     * properly caught and handled.
     *
     * @throws IOException
     * @throws ParseException
     */
@Test
public void testParseExceptions() throws IOException, ParseException {
    BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(new File("./src/test/resources/gazetteers/BadGeoNamesSample.txt")), "UTF-8"));
    String line;
    List<GeoName> geonames = new ArrayList<GeoName>();
    while ((line = r.readLine()) != null) geonames.add(BasicGeoName.parseFromGeoNamesRecord(line));
    r.close();
// if no exceptions are thrown, the test is assumed to have succeeded
}

64. ElementScoreScanner#scan()

Project: cleo
Source File: ElementScoreScanner.java
View license
private void scan(File file, ScoreHandler handler) throws Exception {
    final BufferedReader r = new BufferedReader(new FileReader(file.getAbsolutePath()));
    String line = null;
    while ((line = r.readLine()) != null) {
        String[] parts = line.trim().split("\\s+");
        if (parts.length == 2) {
            try {
                int elementId = Integer.parseInt(parts[0]);
                double elementScore = Double.parseDouble(parts[1]);
                if (handler != null) {
                    handler.handle(elementId, elementScore);
                } else {
                    System.out.printf("%10d %16.8f%n", elementId, elementScore);
                }
            } catch (Exception e) {
                System.err.println(line);
                e.printStackTrace();
            }
        }
    }
    r.close();
}

65. TypeaheadElementStoreBootstrap#loadDataFile()

View license
protected void loadDataFile(File dataFile, String[] dataArray) throws IOException {
    final BufferedReader r = new BufferedReader(new FileReader(dataFile.getAbsolutePath()));
    String line = null;
    while ((line = r.readLine()) != null) {
        line = line.trim().replaceAll("\\s+", " ");
        int ind = line.indexOf(' ');
        if (ind > 0) {
            try {
                int source = Integer.parseInt(line.substring(0, ind));
                if (indexStart <= source && source < indexEnd) {
                    String rest = line.substring(ind + 1).trim();
                    if (rest.length() > 0) {
                        dataArray[source - indexStart] = rest;
                    }
                }
            } catch (Exception e) {
                System.err.println(line);
                e.printStackTrace();
            }
        }
    }
    r.close();
}

66. SimpleTermsExtractor#extract()

Project: cleo
Source File: SimpleTermsExtractor.java
View license
public void extract(File sourceFile, PrintStream ps) throws IOException {
    final BufferedReader r = new BufferedReader(new FileReader(sourceFile.getAbsolutePath()));
    String line = null;
    while ((line = r.readLine()) != null) {
        line = line.trim().replaceAll("\\s+", " ");
        int ind = line.indexOf(' ');
        if (ind > 0) {
            try {
                int source = Integer.parseInt(line.substring(0, ind));
                String rest = line.substring(ind + 1).trim();
                rest = simplify(rest).replaceAll("\\s+", "|");
                ps.printf("%d %s%n", source, rest);
            } catch (Exception e) {
                System.err.println(line);
                e.printStackTrace();
            }
        }
    }
    r.close();
}

67. ImageMagickProvider#inputStreamToStringList()

Project: clerezza
Source File: ImageMagickProvider.java
View license
private List<String> inputStreamToStringList(InputStream is) throws UnsupportedEncodingException, IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
    List<String> sl = new ArrayList<String>();
    String line;
    while ((line = br.readLine()) != null) {
        sl.add(line);
    }
    br.close();
    return sl;
}

68. Example#httpGet()

Project: cmb
Source File: Example.java
View license
public static String httpGet(String url) throws IOException {
    URL confirmationEndpoint = new URL(url);
    URLConnection conn = confirmationEndpoint.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    String response = "";
    while ((inputLine = in.readLine()) != null) {
        response += inputLine;
    }
    logger.info(response);
    in.close();
    return response;
}

69. ResUtils#getRawString()

Project: CNode-Material-Design
Source File: ResUtils.java
View license
public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException {
    InputStream is = context.getResources().openRawResource(rawId);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
    }
    sb.deleteCharAt(sb.length() - 1);
    reader.close();
    return sb.toString();
}

70. PandoraBotsUtil#responseContent()

View license
public static String responseContent(String url) throws Exception {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet();
    request.setURI(new URI(url));
    InputStream is = client.execute(request).getEntity().getContent();
    BufferedReader inb = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder("");
    String line;
    String NL = System.getProperty("line.separator");
    while ((line = inb.readLine()) != null) {
        sb.append(line).append(NL);
    }
    inb.close();
    return sb.toString();
}

71. ArchiveReadTest#setUpFileList()

View license
@BeforeClass
public static void setUpFileList() throws Exception {
    assertTrue(ARCDIR.exists());
    final File listing = new File(ARCDIR, "files.txt");
    assertTrue("files.txt is readable", listing.canRead());
    final BufferedReader br = new BufferedReader(new FileReader(listing));
    String line;
    while ((line = br.readLine()) != null) {
        if (!line.startsWith("#")) {
            FILELIST.add(line);
        }
    }
    br.close();
}

72. LongPathTest#setUpFileList()

Project: commons-compress
Source File: LongPathTest.java
View license
@BeforeClass
public static void setUpFileList() throws Exception {
    assertTrue(ARCDIR.exists());
    final File listing = new File(ARCDIR, "files.txt");
    assertTrue("files.txt is readable", listing.canRead());
    final BufferedReader br = new BufferedReader(new FileReader(listing));
    String line;
    while ((line = br.readLine()) != null) {
        if (!line.startsWith("#")) {
            FILELIST.add(line);
        }
    }
    br.close();
}

73. LongSymLinkTest#setUpFileList()

View license
@BeforeClass
public static void setUpFileList() throws Exception {
    assertTrue(ARCDIR.exists());
    final File listing = new File(ARCDIR, "files.txt");
    assertTrue("files.txt is readable", listing.canRead());
    final BufferedReader br = new BufferedReader(new FileReader(listing));
    String line;
    while ((line = br.readLine()) != null) {
        if (!line.startsWith("#")) {
            FILELIST.add(line);
        }
    }
    br.close();
}

74. CSVBenchmark#read()

Project: commons-csv
Source File: CSVBenchmark.java
View license
@Benchmark
public int read(final Blackhole bh) throws Exception {
    final BufferedReader in = getReader();
    int count = 0;
    String line;
    while ((line = in.readLine()) != null) {
        count++;
    }
    bh.consume(count);
    in.close();
    return count;
}

75. CSVBenchmark#split()

Project: commons-csv
Source File: CSVBenchmark.java
View license
@Benchmark
public int split(final Blackhole bh) throws Exception {
    final BufferedReader in = getReader();
    int count = 0;
    String line;
    while ((line = in.readLine()) != null) {
        final String[] values = StringUtils.split(line, ',');
        count += values.length;
    }
    bh.consume(count);
    in.close();
    return count;
}

76. CSVBenchmark#parseCommonsCSV()

Project: commons-csv
Source File: CSVBenchmark.java
View license
@Benchmark
public int parseCommonsCSV(final Blackhole bh) throws Exception {
    final BufferedReader in = getReader();
    final CSVFormat format = CSVFormat.DEFAULT.withHeader();
    int count = 0;
    for (final CSVRecord record : format.parse(in)) {
        count++;
    }
    bh.consume(count);
    in.close();
    return count;
}

77. CSVBenchmark#parseGenJavaCSV()

Project: commons-csv
Source File: CSVBenchmark.java
View license
@Benchmark
public int parseGenJavaCSV(final Blackhole bh) throws Exception {
    final BufferedReader in = getReader();
    final CsvReader reader = new CsvReader(in);
    reader.setFieldDelimiter(',');
    int count = 0;
    String[] record = null;
    while ((record = reader.readLine()) != null) {
        count++;
    }
    bh.consume(count);
    in.close();
    return count;
}

78. CSVBenchmark#parseJavaCSV()

Project: commons-csv
Source File: CSVBenchmark.java
View license
@Benchmark
public int parseJavaCSV(final Blackhole bh) throws Exception {
    final BufferedReader in = getReader();
    final com.csvreader.CsvReader reader = new com.csvreader.CsvReader(in, ',');
    reader.setRecordDelimiter('\n');
    int count = 0;
    while (reader.readRecord()) {
        count++;
    }
    bh.consume(count);
    in.close();
    return count;
}

79. CSVBenchmark#parseOpenCSV()

Project: commons-csv
Source File: CSVBenchmark.java
View license
@Benchmark
public int parseOpenCSV(final Blackhole bh) throws Exception {
    final BufferedReader in = getReader();
    final com.opencsv.CSVReader reader = new com.opencsv.CSVReader(in, ',');
    int count = 0;
    while (reader.readNext() != null) {
        count++;
    }
    bh.consume(count);
    in.close();
    return count;
}

80. CSVBenchmark#parseSkifeCSV()

Project: commons-csv
Source File: CSVBenchmark.java
View license
@Benchmark
public int parseSkifeCSV(final Blackhole bh) throws Exception {
    final BufferedReader in = getReader();
    final org.skife.csv.CSVReader reader = new org.skife.csv.SimpleReader();
    reader.setSeperator(',');
    final CountingReaderCallback callback = new CountingReaderCallback();
    reader.parse(in, callback);
    bh.consume(callback);
    in.close();
    return callback.count;
}

81. CSVBenchmark#parseSuperCSV()

Project: commons-csv
Source File: CSVBenchmark.java
View license
@Benchmark
public int parseSuperCSV(final Blackhole bh) throws Exception {
    final BufferedReader in = getReader();
    final CsvListReader reader = new CsvListReader(in, CsvPreference.STANDARD_PREFERENCE);
    int count = 0;
    List<String> record = null;
    while ((record = reader.read()) != null) {
        count++;
    }
    bh.consume(count);
    in.close();
    return count;
}

82. IOUtils#contentEqualsIgnoreEOL()

Project: commons-io
Source File: IOUtils.java
View license
/**
     * Compares the contents of two Readers to determine if they are equal or
     * not, ignoring EOL characters.
     * <p>
     * This method buffers the input internally using
     * <code>BufferedReader</code> if they are not already buffered.
     *
     * @param input1 the first reader
     * @param input2 the second reader
     * @return true if the content of the readers are equal (ignoring EOL differences),  false otherwise
     * @throws NullPointerException if either input is null
     * @throws IOException          if an I/O error occurs
     * @since 2.2
     */
public static boolean contentEqualsIgnoreEOL(final Reader input1, final Reader input2) throws IOException {
    if (input1 == input2) {
        return true;
    }
    final BufferedReader br1 = toBufferedReader(input1);
    final BufferedReader br2 = toBufferedReader(input2);
    String line1 = br1.readLine();
    String line2 = br2.readLine();
    while (line1 != null && line2 != null && line1.equals(line2)) {
        line1 = br1.readLine();
        line2 = br2.readLine();
    }
    return line1 == null ? line2 == null ? true : false : line1.equals(line2);
}

83. DaytimeTCPClient#getTime()

Project: commons-net
Source File: DaytimeTCPClient.java
View license
/**
     * Retrieves the time string from the server and returns it.  The
     * server will have closed the connection at this point, so you should
     * call
     * {@link org.apache.commons.net.SocketClient#disconnect  disconnect }
     * after calling this method.  To retrieve another time, you must
     * initiate another connection with
     * {@link org.apache.commons.net.SocketClient#connect  connect }
     * before calling <code> getTime() </code> again.
     *
     * @return The time string retrieved from the server.
     * @throws IOException  If an error occurs while fetching the time string.
     */
public String getTime() throws IOException {
    int read;
    StringBuilder result = new StringBuilder(__buffer.length);
    BufferedReader reader;
    reader = new BufferedReader(new InputStreamReader(_input_, getCharset()));
    while (true) {
        read = reader.read(__buffer, 0, __buffer.length);
        if (read <= 0) {
            break;
        }
        result.append(__buffer, 0, read);
    }
    return result.toString();
}

84. FingerClient#query()

Project: commons-net
Source File: FingerClient.java
View license
/***
     * Fingers a user at the connected host and returns the output
     * as a String.  You must first connect to a finger server before
     * calling this method, and you should disconnect afterward.
     *
     * @param longOutput Set to true if long output is requested, false if not.
     * @param username  The name of the user to finger.
     * @return The result of the finger query.
     * @throws IOException If an I/O error occurs while reading the socket.
     ***/
public String query(boolean longOutput, String username) throws IOException {
    int read;
    StringBuilder result = new StringBuilder(__buffer.length);
    BufferedReader input;
    input = new BufferedReader(new InputStreamReader(getInputStream(longOutput, username), getCharset()));
    try {
        while (true) {
            read = input.read(__buffer, 0, __buffer.length);
            if (read <= 0) {
                break;
            }
            result.append(__buffer, 0, read);
        }
    } finally {
        input.close();
    }
    return result.toString();
}

85. FTPListParseEngine#readStream()

Project: commons-net
Source File: FTPListParseEngine.java
View license
/**
     * Internal method for reading the input into the <code>entries</code> list.
     * After this method has completed, <code>entries</code> will contain a
     * collection of entries (as defined by
     * <code>FTPFileEntryParser.readNextEntry()</code>), but this may contain
     * various non-entry preliminary lines from the server output, duplicates,
     * and other data that will not be part of the final listing.
     *
     * @param stream The socket stream on which the input will be read.
     * @param encoding The encoding to use.
     *
     * @throws IOException
     *                   thrown on any failure to read the stream
     */
private void readStream(InputStream stream, String encoding) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream, Charsets.toCharset(encoding)));
    String line = this.parser.readNextEntry(reader);
    while (line != null) {
        this.entries.add(line);
        line = this.parser.readNextEntry(reader);
    }
    reader.close();
}

86. NNTPClient#listHelp()

Project: commons-net
Source File: NNTPClient.java
View license
/***
     * List the command help from the server.
     * <p>
     * @return The sever help information.
     * @throws NNTPConnectionClosedException
     *      If the NNTP server prematurely closes the connection as a result
     *      of the client being idle or some other reason causing the server
     *      to send NNTP reply code 400.  This exception may be caught either
     *      as an IOException or independently as itself.
     * @throws IOException  If an I/O error occurs while either sending a
     *      command to the server or receiving a reply from the server.
     ***/
public String listHelp() throws IOException {
    if (!NNTPReply.isInformational(help())) {
        return null;
    }
    StringWriter help = new StringWriter();
    BufferedReader reader = new DotTerminatedMessageReader(_reader_);
    Util.copyReader(reader, help);
    reader.close();
    help.close();
    return help.toString();
}

87. NNTPClient#listOverviewFmt()

Project: commons-net
Source File: NNTPClient.java
View license
/**
     * Send a "LIST OVERVIEW.FMT" command to the server.
     *
     * @return the contents of the Overview format, of {@code null} if the command failed
     * @throws IOException on error
     */
public String[] listOverviewFmt() throws IOException {
    if (!NNTPReply.isPositiveCompletion(sendCommand("LIST", "OVERVIEW.FMT"))) {
        return null;
    }
    BufferedReader reader = new DotTerminatedMessageReader(_reader_);
    String line;
    ArrayList<String> list = new ArrayList<String>();
    while ((line = reader.readLine()) != null) {
        list.add(line);
    }
    reader.close();
    return list.toArray(new String[list.size()]);
}

88. JsonDownloader#downloadJson()

View license
private String downloadJson() throws Exception {
    final StringBuilder jsonContent = new StringBuilder();
    final URLConnection urlConnection = URLConnectionHelper.createConnectionToURL(downloadUrl, requestHeaders);
    final InputStreamReader streamReader = new InputStreamReader(urlConnection.getInputStream());
    final BufferedReader bufferedReader = new BufferedReader(streamReader);
    final char data[] = new char[1024];
    int count;
    while ((count = bufferedReader.read(data)) != -1) {
        jsonContent.append(data, 0, count);
    }
    bufferedReader.close();
    return jsonContent.toString();
}

89. FilesUtility#readFromFile()

View license
/**
     * Read data as string from the provided file.
     *
     * @param file file to read from
     * @return data from file
     * @throws IOException
     */
public static String readFromFile(File file) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
    StringBuilder content = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        content.append(line).append("\n");
    }
    bufferedReader.close();
    return content.toString().trim();
}

90. PTBTokenizerITest#testLargeDataSet()

Project: CoreNLP
Source File: PTBTokenizerITest.java
View license
public void testLargeDataSet() throws IOException {
    BufferedReader goldReader = getReaderFromInJavaNlp("ptblexer.gold");
    List<String> goldResults = new ArrayList<String>();
    for (String line; (line = goldReader.readLine()) != null; ) {
        goldResults.add(line.trim());
    }
    BufferedReader testReader = getReaderFromInJavaNlp("ptblexer.test");
    compareResults(testReader, goldResults);
    testReader = getReaderFromInJavaNlp("ptblexer.crlf.test");
    compareResults(testReader, goldResults);
}

91. StringDictionary#load()

Project: CoreNLP
Source File: StringDictionary.java
View license
/** Loads all saved dictionary entries from disk */
public void load(String path, String prefix) throws java.io.IOException {
    String fileName = path + java.io.File.separator + prefix + "." + mName;
    BufferedReader is = IOUtils.readerFromString(fileName);
    for (String line; (line = is.readLine()) != null; ) {
        ArrayList<String> tokens = SimpleTokenize.tokenize(line);
        if (tokens.size() != 3) {
            throw new RuntimeException("Invalid dictionary line: " + line);
        }
        int index = Integer.parseInt(tokens.get(1));
        int count = Integer.parseInt(tokens.get(2));
        if (index < 0 || count <= 0) {
            throw new RuntimeException("Invalid dictionary line: " + line);
        }
        IndexAndCount ic = new IndexAndCount(index, count);
        mDict.put(tokens.get(0), ic);
        mInverse.put(Integer.valueOf(index), tokens.get(0));
    }
    is.close();
    log.info("Loaded " + mDict.size() + " entries for dictionary \"" + mName + "\".");
}

92. PhraseTable#readPhrases()

Project: CoreNLP
Source File: PhraseTable.java
View license
public void readPhrases(String filename, boolean checkTag, Pattern delimiterPattern) throws IOException {
    Timing timer = new Timing();
    timer.doing("Reading phrases: " + filename);
    BufferedReader br = IOUtils.getBufferedFileReader(filename);
    String line;
    while ((line = br.readLine()) != null) {
        if (checkTag) {
            String[] columns = delimiterPattern.split(line, 2);
            if (columns.length == 1) {
                addPhrase(columns[0]);
            } else {
                addPhrase(columns[0], columns[1]);
            }
        } else {
            addPhrase(line);
        }
    }
    br.close();
    timer.done();
}

93. PhraseTable#readPhrases()

Project: CoreNLP
Source File: PhraseTable.java
View license
public void readPhrases(String filename, int phraseColIndex, int tagColIndex) throws IOException {
    if (phraseColIndex < 0) {
        throw new IllegalArgumentException("Invalid phraseColIndex " + phraseColIndex);
    }
    Timing timer = new Timing();
    timer.doing("Reading phrases: " + filename);
    BufferedReader br = IOUtils.getBufferedFileReader(filename);
    String line;
    while ((line = br.readLine()) != null) {
        String[] columns = tabPattern.split(line);
        String phrase = columns[phraseColIndex];
        String tag = (tagColIndex >= 0) ? columns[tagColIndex] : null;
        addPhrase(phrase, tag);
    }
    br.close();
    timer.done();
}

94. SimpleGoodTuring#readInput()

Project: CoreNLP
Source File: SimpleGoodTuring.java
View license
// static methods -------------------------------------------------------------
/**
   * Reads from STDIN a sequence of lines, each containing two integers,
   * separated by whitespace.  Returns a pair of int arrays containing the
   * values read.
   */
private static int[][] readInput() throws Exception {
    List<Integer> rVals = new ArrayList<>();
    List<Integer> nVals = new ArrayList<>();
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line;
    while ((line = in.readLine()) != null) {
        String[] tokens = line.trim().split("\\s+");
        if (tokens.length != 2)
            throw new Exception("Line doesn't contain two tokens: " + line);
        Integer r = Integer.valueOf(tokens[0]);
        Integer n = Integer.valueOf(tokens[1]);
        rVals.add(r);
        nVals.add(n);
    }
    in.close();
    int[][] result = new int[2][];
    result[0] = integerList2IntArray(rVals);
    result[1] = integerList2IntArray(nVals);
    return result;
}

95. CollectionUtils#loadCollection()

Project: CoreNLP
Source File: CollectionUtils.java
View license
/**
   * @param file The file to load the List from
   * @param c The Class to instantiate each member of the List. Must have a
   *          String constructor.
   */
public static <T> Collection<T> loadCollection(File file, Class<T> c, CollectionFactory<T> cf) throws Exception {
    Constructor<T> m = c.getConstructor(new Class[] { String.class });
    Collection<T> result = cf.newCollection();
    BufferedReader in = new BufferedReader(new FileReader(file));
    String line = in.readLine();
    while (line != null && line.length() > 0) {
        try {
            T o = m.newInstance(line);
            result.add(o);
        } catch (Exception e) {
            log.info("Couldn't build object from line: " + line);
            e.printStackTrace();
        }
        line = in.readLine();
    }
    in.close();
    return result;
}

96. CollectionUtils#loadCollection()

Project: CoreNLP
Source File: CollectionUtils.java
View license
/**
   * Adds the items from the file to the collection.
   *
   * @param <T> The type of the items.
   * @param file The file from which items should be loaded.
   * @param itemClass The class of the items (must have a constructor that accepts a String).
   * @param collection The collection to which items should be added.
   */
public static <T> void loadCollection(File file, Class<T> itemClass, Collection<T> collection) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, IOException {
    Constructor<T> itemConstructor = itemClass.getConstructor(String.class);
    BufferedReader in = new BufferedReader(new FileReader(file));
    String line = in.readLine();
    while (line != null && line.length() > 0) {
        T t = itemConstructor.newInstance(line);
        collection.add(t);
        line = in.readLine();
    }
    in.close();
}

97. InternalFileWriteReadActivity#readFile()

View license
private void readFile(LinearLayout ll) throws IOException {
    FileInputStream fis = openFileInput(fileName);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    String line = "";
    while (null != (line = br.readLine())) {
        TextView tv = new TextView(this);
        tv.setTextSize(24);
        tv.setText(line);
        ll.addView(tv);
    }
    br.close();
}

98. InternalClobTest#transferData()

Project: derby
Source File: InternalClobTest.java
View license
/**
     * Transfers data from the source to the destination.
     */
public static long transferData(Reader src, Writer dest, long charsToCopy) throws IOException {
    BufferedReader in = new BufferedReader(src);
    BufferedWriter out = new BufferedWriter(dest, BUFFER_SIZE);
    char[] bridge = new char[BUFFER_SIZE];
    long charsLeft = charsToCopy;
    int read;
    while ((read = in.read(bridge, 0, (int) Math.min(charsLeft, BUFFER_SIZE))) > 0) {
        out.write(bridge, 0, read);
        charsLeft -= read;
    }
    in.close();
    // Don't close the stream, in case it will be written to again.
    out.flush();
    return charsToCopy - charsLeft;
}

99. RunTest#appendStderr()

Project: derby
Source File: RunTest.java
View license
static void appendStderr(BufferedOutputStream bos, InputStream is) throws IOException {
    PrintWriter tmpPw = new PrintWriter(bos);
    // reader for stderr
    BufferedReader errReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    String s = null;
    int lines = 0;
    while ((s = errReader.readLine()) != null) {
        tmpPw.println(s);
    }
    errReader.close();
    tmpPw.flush();
}

100. SimpleDiff#lineCount()

Project: derby
Source File: SimpleDiff.java
View license
int lineCount(String file) throws IOException {
    BufferedReader input = new BufferedReader(new FileReader(file));
    int count = 0;
    String aLine = input.readLine();
    while (aLine != null) {
        count++;
        aLine = input.readLine();
    }
    input.close();
    return count;
}