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

The following examples show how to use java.io.BufferedReader#ready() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RETest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Finds next test description in a given script.
 * @param br <code>BufferedReader</code> for a script file
 * @return strign tag for next test description
 * @exception IOException if some io problems occured
 */
private String findNextTest(BufferedReader br) throws IOException
{
    String number = "";

    while (br.ready())
    {
        number = br.readLine();
        if (number == null)
        {
            break;
        }
        number = number.trim();
        if (number.startsWith("#"))
        {
            break;
        }
        if (!number.equals(""))
        {
            say("Script error.  Line = " + number);
            System.exit(-1);
        }
    }
    return number;
}
 
Example 2
Source File: FileCache.java    From OpenEphyra with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Read the entries for the given key from the cache.
 * 
 * @param key the key
 * @return the entries, or <code>null</code> if the key is not in the cache
 */
public String[] read(String key) {
	// compute checksum for the key
	String checksum = getMD5(key);
	if (checksum == null) return null;
	
	// read cache entries from a file, using the checksum as the filename
	File file = new File(cacheDir, new String(checksum));
	try {
		ArrayList<String> entries = new ArrayList<String>();
		
		BufferedReader in = new BufferedReader(new FileReader(file));
		while (in.ready()) entries.add(in.readLine());
		in.close();
		
		return entries.toArray(new String[entries.size()]);
	} catch (IOException e) {return null;}  // key is not in the cache
}
 
Example 3
Source File: AtUtil.java    From LPAd_SM-DPPlus_Connector with Apache License 2.0 6 votes vote down vote up
public static String receive(final BufferedReader reader,
                             final int timeOutMs) throws IOException, ModemTimeoutException {
    int tries = timeOutMs / DATA_WAITING_CHECK_PERIOD_MS;
    while (!reader.ready()) {
        try {
            Thread.sleep(DATA_WAITING_CHECK_PERIOD_MS);
        } catch (InterruptedException e) {
            LOG.severe("reception time-out (sleep interrupted)");

            throw new ModemTimeoutException(
                    "waiting for serial port data interrupted");
        }

        if (timeOutMs >= 0 && tries-- <= 0) {
            LOG.severe("reception time-out");

            throw new ModemTimeoutException(
                    "time-out waiting for serial port data");
        }
    }

    final String line = reader.readLine();
    LOG.fine("Received from Modem: " + line);

    return line;
}
 
Example 4
Source File: DartDioClientCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeywords() throws Exception {
    final DartDioClientCodegen codegen = new DartDioClientCodegen();

    List<String> reservedWordsList = new ArrayList<String>();
    try {                                                                                   
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/main/resources/dart/dart-keywords.txt"), Charset.forName("UTF-8")));
        while(reader.ready()) { reservedWordsList.add(reader.readLine()); }
        reader.close();
    } catch (Exception e) {
        String errorString = String.format(Locale.ROOT, "Error reading dart keywords: %s", e);
        Assert.fail(errorString, e);
    }
    
    Assert.assertEquals(reservedWordsList.size() > 20, true);
    Assert.assertEquals(codegen.reservedWords().size() == reservedWordsList.size(), true);
    for(String keyword : reservedWordsList) {
        // reserved words are stored in lowercase 
        Assert.assertEquals(codegen.reservedWords().contains(keyword.toLowerCase(Locale.ROOT)), true, String.format(Locale.ROOT, "%s, part of %s, was not found in %s", keyword, reservedWordsList, codegen.reservedWords().toString()));
    }
}
 
Example 5
Source File: RETest.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Finds next test description in a given script.
 * @param br <code>BufferedReader</code> for a script file
 * @return strign tag for next test description
 * @exception IOException if some io problems occured
 */
private String findNextTest(BufferedReader br) throws IOException
{
    String number = "";

    while (br.ready())
    {
        number = br.readLine();
        if (number == null)
        {
            break;
        }
        number = number.trim();
        if (number.startsWith("#"))
        {
            break;
        }
        if (!number.equals(""))
        {
            say("Script error.  Line = " + number);
            System.exit(-1);
        }
    }
    return number;
}
 
Example 6
Source File: IoTest.java    From java-study with Apache License 2.0 6 votes vote down vote up
/**
 * 写入和读取文件
 * @throws IOException
 */
private static void test3() throws IOException {
	//创建要操作的文件路径和名称  
       String path ="E:/test/hello.txt";
       String str="你好!";
       FileWriter fw = new FileWriter(path);  
       BufferedWriter bw=new BufferedWriter(fw);
       bw.write(str);  
       bw.close();
       fw.close();  
       
       FileReader fr = new FileReader(path);  
       BufferedReader br=new BufferedReader(fr);
       StringBuffer sb=new StringBuffer();
 		while(br.ready()){
 			sb.append((char)br.read());
 		}
       System.out.println("输出:"+sb.toString());
       br.close();
       fr.close();
}
 
Example 7
Source File: Solution.java    From JavaExercises with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String fileIn = reader.readLine();
    String fileOut = reader.readLine();
    reader.close();

    BufferedReader fileReader = new BufferedReader(new FileReader(fileIn));
    BufferedWriter fileWriter = new BufferedWriter(new FileWriter(fileOut));

    while (fileReader.ready()) {
        String str = fileReader.readLine().replaceAll("[\\p{Punct}\\n]", "");
        fileWriter.write(str);
    }

    fileReader.close();
    fileWriter.close();
}
 
Example 8
Source File: SettingsBackupAgent.java    From Study_Android_Demo with Apache License 2.0 6 votes vote down vote up
public static Network readFromStream(BufferedReader in) {
    final Network n = new Network();
    String line;
    try {
        while (in.ready()) {
            line = in.readLine();
            if (line == null || line.startsWith("}")) {
                break;
            }
            n.rememberLine(line);
        }
    } catch (IOException e) {
        return null;
    }
    return n;
}
 
Example 9
Source File: RETest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates testcase for the next test description in the script file.
 * @param br <code>BufferedReader</code> for script file.
 * @return a new tescase or null.
 * @exception IOException if some io problems occured
 */
private RETestCase getNextTestCase(BufferedReader br) throws IOException
{
    // Find next re test case
    final String tag = findNextTest(br);

    // Are we done?
    if (!br.ready())
    {
        return null;
    }

    // Get expression
    final String expr = br.readLine();

    // Get test information
    final String matchAgainst = br.readLine();
    final boolean badPattern = "ERR".equals(matchAgainst);
    boolean shouldMatch = false;
    int expectedParenCount = 0;
    String[] expectedParens = null;

    if (!badPattern) {
        shouldMatch = getExpectedResult(br.readLine().trim());
        if (shouldMatch) {
            expectedParenCount = Integer.parseInt(br.readLine().trim());
            expectedParens = new String[expectedParenCount];
            for (int i = 0; i < expectedParenCount; i++) {
                expectedParens[i] = br.readLine();
            }
        }
    }

    return new RETestCase(this, tag, expr, matchAgainst, badPattern,
                          shouldMatch, expectedParens);
}
 
Example 10
Source File: RETest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates testcase for the next test description in the script file.
 * @param br <code>BufferedReader</code> for script file.
 * @return a new tescase or null.
 * @exception IOException if some io problems occured
 */
private RETestCase getNextTestCase(BufferedReader br) throws IOException
{
    // Find next re test case
    final String tag = findNextTest(br);

    // Are we done?
    if (!br.ready())
    {
        return null;
    }

    // Get expression
    final String expr = br.readLine();

    // Get test information
    final String matchAgainst = br.readLine();
    final boolean badPattern = "ERR".equals(matchAgainst);
    boolean shouldMatch = false;
    int expectedParenCount = 0;
    String[] expectedParens = null;

    if (!badPattern) {
        shouldMatch = getExpectedResult(br.readLine().trim());
        if (shouldMatch) {
            expectedParenCount = Integer.parseInt(br.readLine().trim());
            expectedParens = new String[expectedParenCount];
            for (int i = 0; i < expectedParenCount; i++) {
                expectedParens[i] = br.readLine();
            }
        }
    }

    return new RETestCase(this, tag, expr, matchAgainst, badPattern,
                          shouldMatch, expectedParens);
}
 
Example 11
Source File: GraphDimacsFileWriterTest.java    From LogicNG with Apache License 2.0 5 votes vote down vote up
private void assertMapFilesEqual(final File expected, final File actual) throws IOException {
  final BufferedReader expReader = new BufferedReader(new FileReader(expected));
  final BufferedReader actReader = new BufferedReader(new FileReader(actual));
  for (int lineNumber = 1; expReader.ready() && actReader.ready(); lineNumber++)
    softly.assertThat(actReader.readLine()).as("Line " + lineNumber + " not equal").isEqualTo(expReader.readLine());
  if (expReader.ready())
    softly.fail("Missing line(s) found, starting with \"" + expReader.readLine() + "\"");
  if (actReader.ready())
    softly.fail("Additional line(s) found, starting with \"" + actReader.readLine() + "\"");
}
 
Example 12
Source File: HTTPPostURL.java    From perf-harness with MIT License 5 votes vote down vote up
/** Fetch the HTML content of the page as simple text. */
public String putPageContent(String payload, Boolean auth, String authStringEnc) throws IOException {				String result = null;	
	try {
		HttpURLConnection connection = (HttpURLConnection) fURL.openConnection();
		connection.setRequestMethod("POST");
		if (auth != false) {
			connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
		}
		connection.setDoInput(true);
		connection.setDoOutput(true);			
		connection.setRequestProperty("Content-Type", "application/json");
		connection.connect();		
		OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
		if (payload == "") {
			Log.logger.log(Level.FINE, "Putting: replaydestination=MyDestination");
			out.write("replaydestination=MyDestination");
		} else {
			Log.logger.log(Level.FINE, "Putting: " + payload);
			out.write(payload);
		}
		out.close();

		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		while (br.ready()) {
			result = br.readLine();
    	  Log.logger.log(Level.FINE, result);
      }
		br.close();

	} catch (IOException ex) {
		Log.logger.log(Level.SEVERE, "Cannot open connection to " + fURL.toString());
		throw ex;
	}
	return result;
}
 
Example 13
Source File: NuggetEvaluationFilter.java    From OpenEphyra with GNU General Public License v2.0 5 votes vote down vote up
/**
 * load the nuggets from the answer file
 */
private static void loadNuggets() {
	try {
		BufferedReader br = new BufferedReader(new FileReader("./res/testdata/trec/trec15answers_other"));
		String targetID = null;
		ArrayList<TRECNugget> nuggets = new ArrayList<TRECNugget>();
		
		while (br.ready()) {
			String line = br.readLine();
			if ((line != null) && (line.length() != 0) && !line.startsWith("Qid")) {
				String[] parts = line.split("((\\s++)|\\.)", 5);
				
				TRECNugget nugget = new TRECNugget(parts[0], parts[1], parts[2], parts[3], parts[4]);
				
				if (!nugget.targetID.equals(targetID)) {
					if (targetID != null) nuggetsByTargetID.put(targetID, nuggets);
					targetID = nugget.targetID;
					nuggets = new ArrayList<TRECNugget>();
				}
				
				nuggets.add(nugget);
			}
		}
		
		if (targetID != null) nuggetsByTargetID.put(targetID, nuggets);
		
		br.close();
	} catch (Exception e) {
		System.out.println(e.getClass().getName() + " (" + e.getMessage() + ") while loading nuggets");
		e.printStackTrace(System.out);
	}
}
 
Example 14
Source File: HashemInstrumentTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
String readLinesList(BufferedReader br) throws IOException {
    List<String> lines = new ArrayList<>();
    while (br.ready()) {
        String line = br.readLine();
        if (line == null) {
            break;
        }
        lines.add(line);
    }
    return lines.toString();
}
 
Example 15
Source File: GooglePlusTypeConverterIT.java    From streams with Apache License 2.0 5 votes vote down vote up
@Test(dependsOnGroups = {"GPlusUserActivityProviderIT"})
public void testProcessActivity() throws IOException, ActivitySerializerException {
  Config application = ConfigFactory.parseResources("GooglePlusTypeConverterIT.conf").withFallback(ConfigFactory.load());
  String inputResourcePath = application.getConfig("testProcessActivity").getString("inputResourcePath");
  InputStream is = GooglePlusTypeConverterIT.class.getResourceAsStream(inputResourcePath);
  InputStreamReader isr = new InputStreamReader(is);
  BufferedReader br = new BufferedReader(isr);

  while (br.ready()) {
    String line = br.readLine();
    if (!StringUtils.isEmpty(line)) {
      LOGGER.info("raw: {}", line);
      Activity activity = new Activity();

      com.google.api.services.plus.model.Activity gPlusActivity = objectMapper.readValue(line, com.google.api.services.plus.model.Activity.class);
      StreamsDatum streamsDatum = new StreamsDatum(gPlusActivity);

      assertNotNull(streamsDatum.getDocument());

      List<StreamsDatum> retList = googlePlusTypeConverter.process(streamsDatum);
      GooglePlusActivityUtil.updateActivity(gPlusActivity, activity);

      assertEquals(retList.size(), 1);
      assertTrue(retList.get(0).getDocument() instanceof Activity);
      assertEquals(activity, retList.get(0).getDocument());
    }
  }
}
 
Example 16
Source File: TestaArquivoAula.java    From dctb-utfpr-2018-1 with Apache License 2.0 5 votes vote down vote up
public static void leResultado(File pasta)throws IOException{
    File arquivo = new File(pasta, "log.txt");
    FileReader leitor = new FileReader(arquivo);
    BufferedReader leitorbuff = new BufferedReader(leitor);
    while(leitorbuff.ready()){
        System.out.println(leitorbuff.readLine());
    }
    leitorbuff.close();
}
 
Example 17
Source File: ScriptTest.java    From bitherj with Apache License 2.0 5 votes vote down vote up
@Test
    public void testDataDrivenValidScripts() throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(
                getClass().getResourceAsStream("script_valid.json"), Charset.forName("UTF-8")));
//        NetworkParameters params = TestNet3Params.get();

        // Poor man's JSON parser (because pulling in a lib for this is overkill)
        String script = "";
        while (in.ready()) {
            String line = in.readLine();
            if (line == null || line.equals("")) continue;
            script += line;
            if (line.equals("]") && script.equals("]") && !in.ready())
                break; // ignore last ]
            if (line.trim().endsWith("],") || line.trim().endsWith("]")) {
                String[] scripts = script.split(",");

                scripts[0] = scripts[0].replaceAll("[\"\\[\\]]", "").trim();
                scripts[1] = scripts[1].replaceAll("[\"\\[\\]]", "").trim();
                Script scriptSig = parseScriptString(scripts[0]);
                Script scriptPubKey = parseScriptString(scripts[1]);

                try {
                    scriptSig.correctlySpends(new Tx(), 0, scriptPubKey, true);
                } catch (ScriptException e) {
                    System.err.println("scriptSig: " + scripts[0]);
                    System.err.println("scriptPubKey: " + scripts[1]);
                    System.err.flush();
                    throw e;
                }
                script = "";
            }
        }
        in.close();
    }
 
Example 18
Source File: Solution.java    From JavaRushTasks with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    BufferedReader conReader = new BufferedReader(new InputStreamReader(System.in));
    String fileName = conReader.readLine(); //"e:\\8.txt";
    conReader.close();

    BufferedReader fileReader = new BufferedReader(new FileReader(fileName));

    while (fileReader.ready()) {
        String line = fileReader.readLine();
        StringBuffer a = new StringBuffer(line);
        System.out.println(a.reverse());
    }
    fileReader.close();
}
 
Example 19
Source File: InstagramUserInfoDataConverterIT.java    From streams with Apache License 2.0 4 votes vote down vote up
@Test(dependsOnGroups = "InstagramUserInfoProviderIT")
public void InstagramUserInfoDataConverterIT() throws Exception {
  InputStream is = InstagramUserInfoDataConverterIT.class.getResourceAsStream("/InstagramUserInfoProviderIT.stdout.txt");
  InputStreamReader isr = new InputStreamReader(is);
  BufferedReader br = new BufferedReader(isr);

  PrintStream outStream = new PrintStream(
      new BufferedOutputStream(
          new FileOutputStream("target/test-classes/InstagramUserInfoDataConverterIT.txt")));

  try {
    while (br.ready()) {
      String line = br.readLine();
      if (!StringUtils.isEmpty(line)) {

        LOGGER.info("raw: {}", line);

        UserInfo userInfoData = mapper.readValue(line, UserInfo.class);

        ActivityObjectConverter<UserInfo> converter = new InstagramUserInfoDataConverter();

        ActivityObject activityObject = converter.toActivityObject(userInfoData);

        LOGGER.info("activityObject: {}", activityObject.toString());

        assertThat(activityObject, is(not(nullValue())));

        assertThat(activityObject.getId(), is(not(nullValue())));
        assertThat(activityObject.getImage(), is(not(nullValue())));
        assertThat(activityObject.getDisplayName(), is(not(nullValue())));
        assertThat(activityObject.getSummary(), is(not(nullValue())));

        Map<String, Object> extensions = (Map<String, Object>)activityObject.getAdditionalProperties().get("extensions");
        assertThat(extensions, is(not(nullValue())));
        assertThat(extensions.get("following"), is(not(nullValue())));
        assertThat(extensions.get("followers"), is(not(nullValue())));
        assertThat(extensions.get("screenName"), is(not(nullValue())));
        assertThat(extensions.get("posts"), is(not(nullValue())));

        assertThat(activityObject.getAdditionalProperties().get("handle"), is(not(nullValue())));
        assertThat(activityObject.getId(), is(not(nullValue())));
        assertThat(activityObject.getUrl(), is(not(nullValue())));

        assertThat(activityObject.getAdditionalProperties().get("provider"), is(not(nullValue())));

        outStream.println(mapper.writeValueAsString(activityObject));

      }
    }
    outStream.flush();

  } catch ( Exception ex ) {
    LOGGER.error("Exception: ", ex);
    outStream.flush();
    Assert.fail();
  }
}
 
Example 20
Source File: BackboneOnSolverTest.java    From LogicNG with Apache License 2.0 4 votes vote down vote up
@Test
public void testRealFormulaIncrementalDecremental1() throws IOException, ParserException {
  if (this.solver.underlyingSolver() instanceof MiniSat2Solver) {
    this.solver.reset();
    final Formula formula = FormulaReader.readPseudoBooleanFormula("src/test/resources/formulas/large_formula.txt", f);
    this.solver.add(formula);
    final SolverState state = this.solver.saveState();
    final List<String> expectedBackbones = new ArrayList<>();
    final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/backbones/backbone_large_formula.txt"));
    while (reader.ready()) {
      expectedBackbones.add(reader.readLine());
    }
    reader.close();
    Backbone backbone = this.solver.backbone(formula.variables());
    assertThat(backbone.getCompleteBackbone()).isEqualTo(parseBackbone(expectedBackbones.get(0)));
    this.solver.add(f.variable("v411"));
    backbone = this.solver.backbone(formula.variables());
    assertThat(backbone.getCompleteBackbone()).isEqualTo(parseBackbone(expectedBackbones.get(1)));
    assertThat(backbone.isSat()).isTrue();

    this.solver.loadState(state);
    this.solver.add(f.parse("v411 & v385"));
    backbone = this.solver.backbone(formula.variables());
    assertThat(backbone.getCompleteBackbone()).isEqualTo(parseBackbone(expectedBackbones.get(2)));
    assertThat(backbone.isSat()).isTrue();

    this.solver.loadState(state);
    this.solver.add(f.parse("v411 & v385 & v275"));
    backbone = this.solver.backbone(formula.variables());
    assertThat(backbone.getCompleteBackbone()).isEqualTo(parseBackbone(expectedBackbones.get(3)));
    assertThat(backbone.isSat()).isTrue();

    this.solver.loadState(state);
    this.solver.add(f.parse("v411 & v385 & v275 & v188"));
    backbone = this.solver.backbone(formula.variables());
    assertThat(backbone.getCompleteBackbone()).isEqualTo(parseBackbone(expectedBackbones.get(4)));
    assertThat(backbone.isSat()).isTrue();

    this.solver.loadState(state);
    this.solver.add(f.parse("v411 & v385 & v275 & v188 & v103"));
    backbone = this.solver.backbone(formula.variables());
    assertThat(backbone.getCompleteBackbone()).isEqualTo(parseBackbone(expectedBackbones.get(5)));
    assertThat(backbone.isSat()).isTrue();

    this.solver.loadState(state);
    this.solver.add(f.parse("v411 & v385 & v275 & v188 & v103 & v404"));
    backbone = this.solver.backbone(formula.variables());
    assertThat(backbone.getCompleteBackbone()).isEmpty();
    assertThat(backbone.isSat()).isFalse();
  }
}