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. 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();
}

3. 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();
}

4. 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();
}

5. 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();
}

6. 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();
}

7. 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());
}

8. 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();
}

9. 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;
}

10. 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();
}

11. 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;
}

12. 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();
}

13. 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();
}

14. 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");
    }
}

15. 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());
}

16. 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());
}

17. 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");
    }
}

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. DBSegUtils#generateSampleInfoInserts()

Project: igv
Source File: DBSegUtils.java
View license
static void generateSampleInfoInserts(String file) throws IOException {
    BufferedReader reader = ParsingUtils.openBufferedReader(file);
    String nextLine;
    while ((nextLine = reader.readLine()) != null) {
        String[] tokens = nextLine.split("\t");
        if (tokens.length > 6) {
            System.out.print("INSERT INTO `SAMPLE_INFO` VALUES (");
            for (int i = 0; i < tokens.length; i++) {
                String val = tokens[i].equals("NA") ? "" : tokens[i];
                System.out.print("'" + val + "'");
                if (i < tokens.length - 1) {
                    System.out.print(", ");
                }
            }
            System.out.println(");");
        }
    }
    reader.close();
}

22. TestMapReduceLocal#readFile()

Project: hadoop-20
Source File: TestMapReduceLocal.java
View license
public static String readFile(String name) throws IOException {
    DataInputStream f = localFs.open(new Path(TEST_ROOT_DIR + "/" + name));
    BufferedReader b = new BufferedReader(new InputStreamReader(f));
    StringBuilder result = new StringBuilder();
    String line = b.readLine();
    while (line != null) {
        result.append(line);
        result.append('\n');
        line = b.readLine();
    }
    b.close();
    return result.toString();
}

23. ApplicationExitUtil#waitForKeyPressToCleanlyExit()

View license
public static void waitForKeyPressToCleanlyExit(ConfigurableApplicationContext ctx) throws IOException {
    // NOTE: In Eclipse, the Shutdown Hooks are not invoked on exit (red
    // button).. In the case of MariaDB4j that's a problem because then the
    // mysqld won't be stopped, so:
    // (@see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38016)
    System.out.println("\nHit Enter to quit...");
    // NOTE: In Eclipse, System.console() is not available.. so:
    // (@see https://bugs.eclipse.org/bugs/show_bug.cgi?id=122429)
    BufferedReader d = new BufferedReader(new InputStreamReader(System.in));
    d.readLine();
    ctx.stop();
    ctx.close();
}

24. GradeLevelBLEU#loadSources()

View license
// hacky way to add the source sentence as the last reference sentence (in
// accordance with SourceBLEU)
public void loadSources(String filepath) throws IOException {
    String[][] newRefSentences = new String[numSentences][refsPerSen + 1];
    BufferedReader br = new BufferedReader(new FileReader(filepath));
    String line;
    int i = 0;
    while (i < numSentences && (line = br.readLine()) != null) {
        for (int r = 0; r < refsPerSen; ++r) {
            newRefSentences[i][r] = refSentences[i][r];
        }
        newRefSentences[i][refsPerSen] = line.trim();
        i++;
    }
    br.close();
}

25. SARI#loadSources()

Project: incubator-joshua
Source File: SARI.java
View license
public void loadSources(String filepath) throws IOException {
    srcSentences = new String[numSentences];
    // BufferedReader br = new BufferedReader(new FileReader(filepath));
    InputStream inStream = new FileInputStream(new File(filepath));
    BufferedReader br = new BufferedReader(new InputStreamReader(inStream, "utf8"));
    String line;
    int i = 0;
    while (i < numSentences && (line = br.readLine()) != null) {
        srcSentences[i] = line.trim();
        i++;
    }
    br.close();
}

26. QueryTest#compare()

Project: incubator-mrql
Source File: QueryTest.java
View license
private int compare(String file1, String file2) throws Exception {
    BufferedReader reader1 = new BufferedReader(new FileReader(file1));
    BufferedReader reader2 = new BufferedReader(new FileReader(file2));
    String line1 = read_lines(reader1);
    String line2 = read_lines(reader2);
    int i = 1;
    do {
        boolean hm = Config.hadoop_mode;
        Config.hadoop_mode = false;
        MRData v1 = MRQL.query(line1);
        MRData v2 = MRQL.query(line2);
        Config.hadoop_mode = hm;
        if (!equal_value(v1, v2)) {
            System.err.println("*** " + file1 + " (query " + i + "):\nFound: " + v1 + "\nExpected: " + v2);
            return i;
        }
        ;
        line1 = read_lines(reader1);
        line2 = read_lines(reader2);
        i++;
    } while (line1 != "" && line2 != "");
    return 0;
}

27. DataTransform#readHeaderLine()

View license
/**
	 * Method to read the header line from the input data file.
	 * 
	 * @param fs
	 * @param prop
	 * @param smallestFile
	 * @return
	 * @throws IOException
	 */
private static String readHeaderLine(FileSystem fs, CSVFileFormatProperties prop, String smallestFile) throws IOException {
    String line = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(new Path(smallestFile))));
    line = br.readLine();
    br.close();
    if (prop.hasHeader()) {
        // nothing here
        ;
    } else {
        // construct header with default column names, V1, V2, etc.
        int ncol = Pattern.compile(Pattern.quote(prop.getDelim())).split(line, -1).length;
        line = null;
        StringBuilder sb = new StringBuilder();
        sb.append("V1");
        for (int i = 2; i <= ncol; i++) sb.append(prop.getDelim() + "V" + i);
        line = sb.toString();
    }
    return line;
}

28. MVImputeAgent#readReplacement()

View license
// ------------------------------------------------------------------------------------------------
private String readReplacement(int colID, FileSystem fs, Path txMtdDir, TfUtils agents) throws IOException {
    Path path = new Path(txMtdDir + "/Impute/" + agents.getName(colID) + TfUtils.TXMTD_MV_FILE_SUFFIX);
    TfUtils.checkValidInputFile(fs, path, true);
    BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(path)));
    String line = br.readLine();
    String replacement = UtilFunctions.unquote(line.split(TfUtils.TXMTD_SEP)[1]);
    br.close();
    return replacement;
}

29. MapReduceTool#readStringFromHDFSFile()

View license
public static String readStringFromHDFSFile(String filename) throws IOException {
    BufferedReader br = setupInputFile(filename);
    // handle multi-line strings in the HDFS file
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = br.readLine()) != null) {
        sb.append(line);
        sb.append("\n");
    }
    br.close();
    //return string without last character
    return sb.substring(0, sb.length() - 1);
}

30. CPANTest#sanityCheck()

Project: natty
Source File: CPANTest.java
View license
@Test
public void sanityCheck() throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(CPANTest.class.getResourceAsStream("/cpan.txt")));
    String value = null;
    while ((value = reader.readLine()) != null) {
        if (!value.trim().startsWith("#") && value.trim().length() > 0) {
            Parser parser = new Parser();
            List<DateGroup> groups = parser.parse(value);
            Assert.assertEquals(1, groups.size());
            Assert.assertTrue(groups.get(0).getDates().size() > 0);
        }
    }
    reader.close();
}

31. StringHelper#inputStreamToString()

Project: olingo-odata2
Source File: StringHelper.java
View license
public static String inputStreamToString(final InputStream in, final boolean preserveLineBreaks) throws IOException {
    final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
    final StringBuilder stringBuilder = new StringBuilder();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line);
        if (preserveLineBreaks) {
            stringBuilder.append("\n");
        }
    }
    bufferedReader.close();
    final String result = stringBuilder.toString();
    return result;
}

32. StringHelper#inputStreamToStringCRLFLineBreaks()

Project: olingo-odata2
Source File: StringHelper.java
View license
public static String inputStreamToStringCRLFLineBreaks(final InputStream in) throws IOException {
    final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
    final StringBuilder stringBuilder = new StringBuilder();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line);
        stringBuilder.append("\r\n");
    }
    bufferedReader.close();
    final String result = stringBuilder.toString();
    return result;
}

33. BasicBatchITCase#test()

Project: olingo-odata4
Source File: BasicBatchITCase.java
View license
@Test
public void test() throws IOException {
    final String content = getRequest("ESAllPrim(32767)");
    final HttpURLConnection connection = batch(content);
    final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    assertTrue(reader.readLine().contains("batch_"));
    checkMimeHeader(reader);
    blankLine(reader);
    assertEquals("HTTP/1.1 200 OK", reader.readLine());
    assertEquals("OData-Version: 4.0", reader.readLine());
    assertEquals("Content-Type: application/json;odata.metadata=minimal", reader.readLine());
    assertEquals("Content-Length: 605", reader.readLine());
    blankLine(reader);
    reader.close();
}

34. CmdLineIngester#readProdFilesFromStdin()

Project: oodt
Source File: CmdLineIngester.java
View license
private static List<String> readProdFilesFromStdin() {
    List<String> prodFiles = new Vector<String>();
    BufferedReader br;
    br = new BufferedReader(new InputStreamReader(System.in));
    String line = null;
    try {
        while ((line = br.readLine()) != null) {
            prodFiles.add(line);
        }
    } catch (IOException e) {
        LOG.log(Level.WARNING, "Error reading prod file: line: [" + line + "]: Message: " + e.getMessage(), e);
    }
    return prodFiles;
}

35. DeleteProduct#readProdIdsFromStdin()

Project: oodt
Source File: DeleteProduct.java
View license
private static List readProdIdsFromStdin() {
    List prodIds = new Vector();
    BufferedReader br;
    br = new BufferedReader(new InputStreamReader(System.in));
    String line = null;
    try {
        while ((line = br.readLine()) != null) {
            prodIds.add(line);
        }
    } catch (IOException e) {
        LOG.log(Level.WARNING, "Error reading prod id: line: [" + line + "]: Message: " + e.getMessage(), e);
    } finally {
        try {
            br.close();
        } catch (Exception ignore) {
        }
    }
    return prodIds;
}

36. SolrIndexer#readProductIdsFromStdin()

Project: oodt
Source File: SolrIndexer.java
View license
/**
	 * This method reads product identifiers from the standard input.
	 * 
	 * @return Returns a List of product identifiers.
	 */
private static List<String> readProductIdsFromStdin() {
    List<String> productIds = new ArrayList<String>();
    BufferedReader br;
    br = new BufferedReader(new InputStreamReader(System.in));
    String line = null;
    try {
        while ((line = br.readLine()) != null) {
            productIds.add(line);
        }
    } catch (IOException e) {
        LOG.severe("Error reading product id: line: [" + line + "]: Message: " + e.getMessage());
    } finally {
        try {
            br.close();
        } catch (Exception ignore) {
        }
    }
    return productIds;
}

37. Profile#main()

Project: oodt
Source File: Profile.java
View license
/**
	 * Try to parse an XML profile in a file in its XML vocabulary.  If successful,
	 * you get the profile as RDF document (in XML format) to the standard output
	 * after it's been digested by the profile class.  If not, then you get an
	 * exception.
	 *
	 * @param argv Command-line arguments, of which there should be one, the name of XML file containing the profile to parse
	 * @throws Throwable if an error occurs.
	 */
public static void main(String[] argv) throws Throwable {
    if (argv.length != 1) {
        System.err.println("Usage: <profile.xml>");
        System.exit(1);
    }
    StringBuilder b = new StringBuilder();
    BufferedReader reader = new BufferedReader(new FileReader(argv[0]));
    char[] buf = new char[INT];
    int num;
    while ((num = reader.read(buf)) != -1) {
        b.append(buf, 0, num);
    }
    reader.close();
    Profile p = new Profile(b.toString());
    Model model = ModelFactory.createDefaultModel();
    p.addToModel(model);
    OutputStreamWriter writer = new OutputStreamWriter(System.out);
    model.write(writer);
    writer.close();
    System.exit(0);
}

38. ProfileTest#setUp()

Project: oodt
Source File: ProfileTest.java
View license
protected void setUp() throws Exception {
    super.setUp();
    oldProfNS = System.getProperty("jpl.rdf.ns");
    System.setProperty("jpl.rdf.ns", "http://enterprise.jpl.nasa.gov/rdfs/prof.rdf#");
    StringBuilder buffer = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    buffer.append("<!DOCTYPE profile PUBLIC \"").append(Profile.PROFILES_DTD_FPI).append("\" \"").append(Profile.PROFILES_DTD_URL).append("\">\n");
    BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("test.xml")));
    String line;
    while ((line = reader.readLine()) != null) {
        buffer.append(line);
        buffer.append('\n');
    }
    reader.close();
    Document doc = XML.parse(buffer.toString());
    profile1 = new Profile(buffer.toString());
    profile2 = new Profile(doc.getDocumentElement());
}

39. SentenceConfirm#readFile()

Project: open-keychain
Source File: SentenceConfirm.java
View license
List<String> readFile(int resId) throws IOException {
    if (context.getApplicationContext() == null) {
        throw new AssertionError("app context can't be null");
    }
    BufferedReader in = new BufferedReader(new InputStreamReader(context.getApplicationContext().getResources().openRawResource(resId)));
    List<String> words = new ArrayList<>();
    String word = in.readLine();
    while (word != null) {
        words.add(word);
        word = in.readLine();
    }
    in.close();
    return words;
}

40. CmsSitesWebserverThread#executeScript()

View license
/**
     * Executes the webserver script.<p>
     *
     * @throws IOException if something goes wrong
     * @throws InterruptedException if something goes wrong
     */
private void executeScript() throws IOException, InterruptedException {
    File script = new File(m_scriptPath);
    List<String> params = new LinkedList<String>();
    params.add(script.getAbsolutePath());
    params.addAll(m_writtenFiles);
    ProcessBuilder pb = new ProcessBuilder(params.toArray(new String[params.size()]));
    pb.directory(new File(script.getParent()));
    Process pr = pb.start();
    pr.waitFor();
    BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    while (buf.ready()) {
        String line = buf.readLine();
        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(line)) {
            getReport().println(Messages.get().container(Messages.RPT_OUTPUT_WEBSERVER_1, buf.readLine()), I_CmsReport.FORMAT_OK);
        }
    }
}

41. PublicMapping#load()

Project: openjdk
Source File: PublicMapping.java
View license
/**
     * Load a set of mappings from a stream.
     */
public void load(InputStream in) throws IOException {
    InputStreamReader reader = new InputStreamReader(in);
    BufferedReader data = new BufferedReader(reader);
    for (String ln = data.readLine(); ln != null; ln = data.readLine()) {
        if (ln.startsWith("PUBLIC")) {
            int len = ln.length();
            int i = 6;
            while ((i < len) && (ln.charAt(i) != '"')) i++;
            int j = ++i;
            while ((j < len) && (ln.charAt(j) != '"')) j++;
            String id = ln.substring(i, j);
            i = ++j;
            while ((i < len) && ((ln.charAt(i) == ' ') || (ln.charAt(i) == '\t'))) i++;
            j = i + 1;
            while ((j < len) && (ln.charAt(j) != ' ') && (ln.charAt(j) != '\t')) j++;
            String where = ln.substring(i, j);
            put(id, baseStr + where);
        }
    }
    data.close();
}

42. SnapshotTestsExecutor#readFile()

Project: vrapper
Source File: SnapshotTestsExecutor.java
View license
/**
     * Reads an external file into a String, converting the newlines to
     *  {@link VimConstants#REGISTER_NEWLINE}
     */
private String readFile(File start) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(start));
    String line;
    StringBuilder sb = new StringBuilder();
    String newline = VimConstants.REGISTER_NEWLINE;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
        sb.append(newline);
    }
    reader.close();
    if (sb.length() > 0) {
        sb.delete(sb.length() - newline.length(), sb.length());
    }
    return sb.toString();
}

43. StringHelperTest#assertLinesEqual()

View license
public static void assertLinesEqual(final String expected, final String actual) throws IOException {
    final StringReader expectedSr = new StringReader(expected);
    final BufferedReader expectedBr = new BufferedReader(expectedSr);
    final StringReader actualSr = new StringReader(actual);
    final BufferedReader actualBr = new BufferedReader(actualSr);
    String expectedLine;
    String actualLine;
    while ((expectedLine = expectedBr.readLine()) != null) {
        if ((actualLine = actualBr.readLine()) != null) {
            Assert.assertEquals(expectedLine, actualLine);
        } else {
            Assert.fail("'expected' contained more lines than 'actual'.");
        }
    }
    if ((actualLine = actualBr.readLine()) != null) {
        Assert.fail("'actual' contained more lines than 'expected'.");
    }
}

44. IOUtils#readFileFromAssets()

Project: wasp
Source File: IOUtils.java
View license
public static String readFileFromAssets(Context context, String filePath) throws IOException {
    if (TextUtils.isEmpty(filePath)) {
        return null;
    }
    StringBuilder builder = new StringBuilder();
    InputStream inputStream = context.getAssets().open(filePath);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    String str;
    while ((str = reader.readLine()) != null) {
        builder.append(str);
    }
    reader.close();
    return builder.toString();
}

45. FileWriterTest#writeTest()

Project: WhereHows
Source File: FileWriterTest.java
View license
@Test
public void writeTest() throws IOException, SQLException {
    String filePath = "testFile.txt";
    Writer w = new FileWriter(filePath);
    List<Object> sample = new ArrayList<Object>();
    sample.add("aaa");
    sample.add("bbb");
    sample.add("ccc");
    Record record = new SampleDataRecord("/a/b/c", sample);
    System.out.println(record.toCsvString());
    w.append(record);
    w.append(record);
    w.close();
    BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
    String line1 = bufferedReader.readLine();
    String line2 = bufferedReader.readLine();
    Assert.assertEquals(record.toCsvString().trim(), line1);
    Assert.assertEquals(record.toCsvString().trim(), line2);
    bufferedReader.close();
}

46. StockQuote#readResult()

Project: wicket
Source File: StockQuote.java
View license
/**
	 * Reads the response from the http connection.
	 * 
	 * @param connection
	 *            the connection to read the response from
	 * @return the response
	 * @throws IOException
	 */
private String readResult(HttpURLConnection connection) throws IOException {
    InputStream inputStream = connection.getInputStream();
    InputStreamReader isr = new InputStreamReader(inputStream);
    BufferedReader in = new BufferedReader(isr);
    StringBuilder sb = new StringBuilder();
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        sb.append(inputLine);
    }
    in.close();
    return sb.toString();
}

47. MiscUtils#get()

Project: Wurst-Client
Source File: MiscUtils.java
View license
public static String get(URL url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder buffer = new StringBuilder();
    for (String line; (line = input.readLine()) != null; ) {
        buffer.append(line);
        buffer.append("\n");
    }
    input.close();
    return buffer.toString();
}

48. CoinfloorAdaptersTest#testAdaptBalances()

Project: XChange
Source File: CoinfloorAdaptersTest.java
View license
@Test
public void testAdaptBalances() throws ExchangeException, IOException {
    // Read in the JSON from the example resources
    BufferedReader br = new BufferedReader(new FileReader("src/test/resources/account/example-balances-response.json"));
    String result = "", line;
    while ((line = br.readLine()) != null) {
        result += line.trim();
    }
    br.close();
    Map<String, Object> testObj = coinfloorAdapters.adaptBalances(result);
    Assert.assertEquals(BigDecimal.valueOf(100014718, 4), ((Wallet) testObj.get("generic")).getBalance(Currency.BTC).getTotal());
    Assert.assertEquals(BigDecimal.valueOf(931913, 2), ((Wallet) testObj.get("generic")).getBalance(Currency.GBP).getTotal());
}

49. CoinfloorAdaptersTest#testAdaptOpenOrders()

Project: XChange
Source File: CoinfloorAdaptersTest.java
View license
@Test
public void testAdaptOpenOrders() throws ExchangeException, IOException {
    // Read in the JSON from the example resources
    BufferedReader br = new BufferedReader(new FileReader("src/test/resources/trade/example-openOrders-response.json"));
    String result = "", line;
    while ((line = br.readLine()) != null) {
        result += line.trim();
    }
    br.close();
    Map<String, Object> testObj = coinfloorAdapters.adaptOpenOrders(result);
    Assert.assertEquals(BigDecimal.valueOf(10000, 4), ((OpenOrders) testObj.get("generic")).getOpenOrders().get(0).getTradableAmount());
    Assert.assertEquals("211118", ((OpenOrders) testObj.get("generic")).getOpenOrders().get(0).getId());
    Assert.assertEquals("GBP", ((OpenOrders) testObj.get("generic")).getOpenOrders().get(0).getCurrencyPair().counter.getCurrencyCode());
    Assert.assertEquals("BTC", ((OpenOrders) testObj.get("generic")).getOpenOrders().get(0).getCurrencyPair().base.getCurrencyCode());
    Assert.assertEquals(OrderType.BID, ((OpenOrders) testObj.get("generic")).getOpenOrders().get(0).getType());
}

50. CoinfloorAdaptersTest#testAdaptPlaceOrder()

Project: XChange
Source File: CoinfloorAdaptersTest.java
View license
@Test
public void testAdaptPlaceOrder() throws IOException {
    // Read in the JSON from the example resources
    BufferedReader br = new BufferedReader(new FileReader("src/test/resources/trade/example-placeOrder-response.json"));
    String result = "", line;
    while ((line = br.readLine()) != null) {
        result += line.trim();
    }
    br.close();
    Map<String, Object> testObj = coinfloorAdapters.adaptPlaceOrder(result);
    Assert.assertEquals("211120", (String.valueOf(testObj.get("generic"))));
}

51. CoinfloorAdaptersTest#testAdaptTradeVolume()

Project: XChange
Source File: CoinfloorAdaptersTest.java
View license
@Test
public void testAdaptTradeVolume() throws IOException {
    // Read in the JSON from the example resources
    BufferedReader br = new BufferedReader(new FileReader("src/test/resources/account/example-tradeVolume-response.json"));
    String result = "", line;
    while ((line = br.readLine()) != null) {
        result += line.trim();
    }
    br.close();
    Map<String, Object> testObj = coinfloorAdapters.adaptTradeVolume(result);
    Assert.assertEquals(BigDecimal.valueOf(40070, 4), new BigDecimal(String.valueOf(testObj.get("generic"))));
}

52. CoinfloorAdaptersTest#testAdaptTicker()

Project: XChange
Source File: CoinfloorAdaptersTest.java
View license
@Test
public void testAdaptTicker() throws IOException {
    // Read in the JSON from the example resources
    BufferedReader br = new BufferedReader(new FileReader("src/test/resources/marketdata/example-ticker-response.json"));
    String result = "", line;
    while ((line = br.readLine()) != null) {
        result += line.trim();
    }
    br.close();
    Map<String, Object> testObj = coinfloorAdapters.adaptTicker(result);
    Assert.assertEquals(BigDecimal.valueOf(32000, 2), ((Ticker) testObj.get("generic")).getLast());
    Assert.assertEquals(BigDecimal.valueOf(0, 2), ((Ticker) testObj.get("generic")).getHigh());
    Assert.assertEquals(BigDecimal.valueOf(0, 2), ((Ticker) testObj.get("generic")).getLow());
    Assert.assertEquals(BigDecimal.valueOf(33000, 2), ((Ticker) testObj.get("generic")).getAsk());
    Assert.assertEquals(BigDecimal.valueOf(32000, 2), ((Ticker) testObj.get("generic")).getBid());
}

53. CoinfloorAdaptersTest#testAdaptOrders()

Project: XChange
Source File: CoinfloorAdaptersTest.java
View license
@Test
public void testAdaptOrders() throws ExchangeException, IOException {
    // Read in the JSON from the example resources
    BufferedReader br = new BufferedReader(new FileReader("src/test/resources/marketdata/example-orders-response.json"));
    String result = "", line;
    while ((line = br.readLine()) != null) {
        result += line.trim();
    }
    br.close();
    Map<String, Object> testObj = coinfloorAdapters.adaptOrders(result);
    Assert.assertEquals(7, ((OrderBook) testObj.get("generic")).getAsks().size());
    Assert.assertEquals(7, ((OrderBook) testObj.get("generic")).getBids().size());
    Assert.assertEquals(BigDecimal.valueOf(9983, 4), ((OrderBook) testObj.get("generic")).getBids().get(0).getTradableAmount());
}

54. CoinfloorAdaptersTest#testAdaptOrderOpened()

Project: XChange
Source File: CoinfloorAdaptersTest.java
View license
@Test
public void testAdaptOrderOpened() throws IOException {
    // Read in the JSON from the example resources
    BufferedReader br = new BufferedReader(new FileReader("src/test/resources/marketdata/example-orderOpened-update.json"));
    String result = "", line;
    while ((line = br.readLine()) != null) {
        result += line.trim();
    }
    br.close();
    Map<String, Object> testObj = coinfloorAdapters.adaptOrderOpened(result);
    Assert.assertEquals(BigDecimal.valueOf(10000, 4), ((LimitOrder) testObj.get("generic")).getTradableAmount());
    Assert.assertEquals("GBP", ((LimitOrder) testObj.get("generic")).getCurrencyPair().counter.getCurrencyCode());
    Assert.assertEquals("BTC", ((LimitOrder) testObj.get("generic")).getCurrencyPair().base.getCurrencyCode());
}

55. CoinfloorAdaptersTest#testAdaptOrderClosed()

Project: XChange
Source File: CoinfloorAdaptersTest.java
View license
@Test
public void testAdaptOrderClosed() throws IOException {
    // Read in the JSON from the example resources
    BufferedReader br = new BufferedReader(new FileReader("src/test/resources/marketdata/example-orderClosed-update.json"));
    String result = "", line;
    while ((line = br.readLine()) != null) {
        result += line.trim();
    }
    br.close();
    Map<String, Object> testObj = coinfloorAdapters.adaptOrderClosed(result);
    Assert.assertEquals(BigDecimal.valueOf(10000, 4), ((LimitOrder) testObj.get("generic")).getTradableAmount());
    Assert.assertEquals("GBP", ((LimitOrder) testObj.get("generic")).getCurrencyPair().counter.getCurrencyCode());
    Assert.assertEquals("BTC", ((LimitOrder) testObj.get("generic")).getCurrencyPair().base.getCurrencyCode());
}

56. CoinfloorAdaptersTest#testAdaptOrdersMatched()

Project: XChange
Source File: CoinfloorAdaptersTest.java
View license
@Test
public void testAdaptOrdersMatched() throws IOException {
    // Read in the JSON from the example resources
    BufferedReader br = new BufferedReader(new FileReader("src/test/resources/marketdata/example-ordersMatched-update.json"));
    String result = "", line;
    while ((line = br.readLine()) != null) {
        result += line.trim();
    }
    br.close();
    Map<String, Object> testObj = coinfloorAdapters.adaptOrdersMatched(result);
    Assert.assertEquals("211184", ((Trade) testObj.get("generic")).getId());
    Assert.assertEquals(BigDecimal.valueOf(4768, 4), ((Trade) testObj.get("generic")).getTradableAmount());
    Assert.assertEquals("GBP", ((Trade) testObj.get("generic")).getCurrencyPair().counter.getCurrencyCode());
    Assert.assertEquals("BTC", ((Trade) testObj.get("generic")).getCurrencyPair().base.getCurrencyCode());
    Assert.assertEquals(OrderType.ASK, ((Trade) testObj.get("generic")).getType());
}

57. CoinfloorAdaptersTest#testAdaptBalancesChanged()

Project: XChange
Source File: CoinfloorAdaptersTest.java
View license
@Test
public void testAdaptBalancesChanged() throws IOException {
    // Read in the JSON from the example resources
    BufferedReader br = new BufferedReader(new FileReader("src/test/resources/account/example-balances-update.json"));
    String result = "", line;
    while ((line = br.readLine()) != null) {
        result += line.trim();
    }
    br.close();
    Map<String, Object> testObj = coinfloorAdapters.adaptBalancesChanged(result);
    Assert.assertEquals(BigDecimal.valueOf(990000, 2), ((Wallet) testObj.get("generic")).getBalance(Currency.GBP).getTotal());
}

58. Util#getPublicKey()

Project: XPrivacy
Source File: Util.java
View license
private static PublicKey getPublicKey(Context context) throws Throwable {
    // Read public key
    String sPublicKey = "";
    InputStreamReader isr = new InputStreamReader(context.getAssets().open("XPrivacy_public_key.txt"), "UTF-8");
    BufferedReader br = new BufferedReader(isr);
    String line = br.readLine();
    while (line != null) {
        if (!line.startsWith("-----"))
            sPublicKey += line;
        line = br.readLine();
    }
    br.close();
    isr.close();
    // Create public key
    byte[] bPublicKey = Base64.decode(sPublicKey, Base64.NO_WRAP);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec encodedPubKeySpec = new X509EncodedKeySpec(bPublicKey);
    return keyFactory.generatePublic(encodedPubKeySpec);
}

59. ICUTokenizerFactory#parseRules()

View license
private BreakIterator parseRules(String filename, ResourceLoader loader) throws IOException {
    StringBuilder rules = new StringBuilder();
    InputStream rulesStream = loader.openResource(filename);
    BufferedReader reader = new BufferedReader(IOUtils.getDecodingReader(rulesStream, StandardCharsets.UTF_8));
    String line = null;
    while ((line = reader.readLine()) != null) {
        if (!line.startsWith("#"))
            rules.append(line);
        rules.append('\n');
    }
    reader.close();
    return new RuleBasedBreakIterator(rules.toString());
}

60. RBBIRuleCompiler#getRules()

Project: lucene-solr
Source File: RBBIRuleCompiler.java
View license
static String getRules(File ruleFile) throws IOException {
    StringBuilder rules = new StringBuilder();
    InputStream in = new FileInputStream(ruleFile);
    BufferedReader cin = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
    String line = null;
    while ((line = cin.readLine()) != null) {
        if (!line.startsWith("#"))
            rules.append(line);
        rules.append('\n');
    }
    cin.close();
    in.close();
    return rules.toString();
}

61. LookupBenchmarkTest#readTop50KWiki()

View license
/**
   * Collect the multilingual input for benchmarks/ tests.
   */
public static List<Input> readTop50KWiki() throws Exception {
    List<Input> input = new ArrayList<>();
    URL resource = LookupBenchmarkTest.class.getResource("Top50KWiki.utf8");
    assert resource != null : "Resource missing: Top50KWiki.utf8";
    String line = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(resource.openStream(), UTF_8));
    while ((line = br.readLine()) != null) {
        int tab = line.indexOf('|');
        assertTrue("No | separator?: " + line, tab >= 0);
        int weight = Integer.parseInt(line.substring(tab + 1));
        String key = line.substring(0, tab);
        input.add(new Input(key, weight));
    }
    br.close();
    return input;
}

62. VocabularyAssert#assertVocabulary()

Project: lucene-solr
Source File: VocabularyAssert.java
View license
/** Run a vocabulary test against two data files. */
public static void assertVocabulary(Analyzer a, InputStream voc, InputStream out) throws IOException {
    BufferedReader vocReader = new BufferedReader(new InputStreamReader(voc, StandardCharsets.UTF_8));
    BufferedReader outputReader = new BufferedReader(new InputStreamReader(out, StandardCharsets.UTF_8));
    String inputWord = null;
    while ((inputWord = vocReader.readLine()) != null) {
        String expectedWord = outputReader.readLine();
        Assert.assertNotNull(expectedWord);
        BaseTokenStreamTestCase.checkOneTerm(a, inputWord, expectedWord);
    }
}

63. TestReplicationHandler#copyFile()

View license
/**
   * character copy of file using UTF-8. If port is non-null, will be substituted any time "TEST_PORT" is found.
   */
private static void copyFile(File src, File dst, Integer port, boolean internalCompression) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(src), StandardCharsets.UTF_8));
    Writer out = new OutputStreamWriter(new FileOutputStream(dst), StandardCharsets.UTF_8);
    for (String line = in.readLine(); null != line; line = in.readLine()) {
        if (null != port)
            line = line.replace("TEST_PORT", port.toString());
        line = line.replace("COMPRESSION", internalCompression ? "internal" : "false");
        out.write(line);
    }
    in.close();
    out.close();
}

64. 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();
}

65. 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();
}

66. 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();
}

67. 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();
}

68. 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);
}

69. 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();
}

70. 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();
}

71. 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();
}

72. 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));
}

73. 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();
}

74. 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();
}

75. 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;
}

76. 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;
}

77. 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;
}

78. 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;
}

79. 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;
}

80. 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);
}

81. 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();
}

82. 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();
}

83. 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();
}

84. 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();
}

85. 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()]);
}

86. 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();
}

87. 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();
}

88. 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);
}

89. 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 + "\".");
}

90. 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();
}

91. 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();
}

92. 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;
}

93. 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();
}

94. 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;
}

95. 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;
}

96. 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;
}

97. 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;
}

98. ClobTest#transferData()

Project: derby
Source File: ClobTest.java
View license
/**
     * Transfer data from a source Reader to a destination Writer.
     *
     * @param source source data
     * @param dest destination to write to
     * @param tz buffer size in number of characters. Must be 1 or greater.
     * @return Number of characters read from the source data. This should equal the
     *      number of characters written to the destination.
     */
private int transferData(Reader source, Writer dest, int tz) throws IOException {
    if (tz < 1) {
        throw new IllegalArgumentException("Buffer size must be 1 or greater: " + tz);
    }
    BufferedReader in = new BufferedReader(source);
    BufferedWriter out = new BufferedWriter(dest, tz);
    char[] bridge = new char[tz];
    int total = 0;
    int read;
    while ((read = in.read(bridge, 0, tz)) != -1) {
        out.write(bridge, 0, read);
        total += read;
    }
    in.close();
    // Don't close the stream, in case it will be written to again.
    out.flush();
    return total;
}

99. 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();
}

100. 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();
}