Java Code Examples for java.io.BufferedReader.readLine()

The following are Jave code examples for showing how to use readLine() of the java.io.BufferedReader class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: cyberduck   File: FireFtpBookmarkCollection.java   View Source Code Vote up 7 votes
/**
 * Read invalid JSON format.
 */
protected void read(final ProtocolFactory protocols, final Local file) throws AccessDeniedException {
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(file.getInputStream(), Charset.forName("UTF-8")));
        try {
            String l;
            while((l = in.readLine()) != null) {
                Matcher array = Pattern.compile("\\[(.*?)\\]").matcher(l);
                while(array.find()) {
                    Matcher entries = Pattern.compile("\\{(.*?)\\}").matcher(array.group(1));
                    while(entries.find()) {
                        final String entry = entries.group(1);
                        this.read(protocols, entry);
                    }
                }
            }
        }
        finally {
            IOUtils.closeQuietly(in);
        }
    }
    catch(IOException e) {
        throw new AccessDeniedException(e.getMessage(), e);
    }
}
 
Example 2
Project: hacker-rank   File: Java_loops_2.java   View Source Code Vote up 6 votes
public static void main(String ... ags)throws Exception
{
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	int n = Integer.parseInt(in.readLine());
	for(int i=0;i<n;i++)
	{
		StringTokenizer tk = new StringTokenizer(in.readLine());
		int a = Integer.parseInt(tk.nextToken());
		int b = Integer.parseInt(tk.nextToken());
		int c = Integer.parseInt(tk.nextToken());
		int sum=a+b;
		System.out.print(sum +" ");
		for(int j=1;j<c;j++)
		{
			sum = sum+(power(j)*b);
			System.out.print(sum + " ");
		}
		System.out.println();
	}
}
 
Example 3
Project: Progetto-C   File: PackedSpriteSheet.java   View Source Code Vote up 6 votes
/**
 * Load the definition file and parse each of the sections
 * 
 * @param def The location of the definitions file
 * @param trans The color to be treated as transparent
 * @throws SlickException Indicates a failure to read or parse the definitions file
 * or referenced image.
 */
private void loadDefinition(String def, Color trans) throws SlickException {
	BufferedReader reader = new BufferedReader(new InputStreamReader(ResourceLoader.getResourceAsStream(def)));

	try {
		image = new Image(basePath+reader.readLine(), false, filter, trans);
		while (reader.ready()) {
			if (reader.readLine() == null) {
				break;
			}
			
			Section sect = new Section(reader);
			sections.put(sect.name, sect);
			
			if (reader.readLine() == null) {
				break;
			}
		}
	} catch (Exception e) {
		Log.error(e);
		throw new SlickException("Failed to process definitions file - invalid format?", e);
	}
}
 
Example 4
Project: connor41-etfuturum2   File: OceanMonument.java   View Source Code Vote up 6 votes
public static void makeMap() {
	try {
		InputStream is = EtFuturum.class.getResourceAsStream("/assets/OceanMonument.txt");
		BufferedReader br = new BufferedReader(new InputStreamReader(is));

		String s;
		while ((s = br.readLine()) != null) {
			String[] data = s.split("-");
			data[0] = data[0].trim();
			data[0] = data[0].substring(1, data[0].length() - 1);

			data[1] = data[1].trim();

			String[] coords = data[0].split(",");

			WorldCoord key = new WorldCoord(Integer.parseInt(coords[0].trim()), Integer.parseInt(coords[1].trim()), Integer.parseInt(coords[2].trim()));
			int value = Integer.parseInt(data[1]);

			map.put(key, value);
		}

		br.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 5
Project: JavaRushTasks   File: Solution.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    while (true) {
        String name = reader.readLine();
        if (name.isEmpty()) break;

        int age = Integer.parseInt(reader.readLine());
        int weight = Integer.parseInt(reader.readLine());
        int tailLength = Integer.parseInt(reader.readLine());

        Cat cat = new Cat(name, age, weight, tailLength);
        CATS.add(cat);
    }

    printList();
}
 
Example 6
Project: RhydoJudge   File: ConnectionFactory.java   View Source Code Vote up 6 votes
public static void obterDadosBD() throws IOException{
    try {
        FileReader conf = new FileReader("config.txt");
        BufferedReader lerArq = new BufferedReader(conf);
        ConnectionFactory.DRIVER = lerArq.readLine();
        ConnectionFactory.URL = lerArq.readLine();
        ConnectionFactory.USER = lerArq.readLine();
        ConnectionFactory.PASS = lerArq.readLine();
        conf.close();
        
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null,"Erro ao abrir o arquivo config.txt");
    }
    
   
}
 
Example 7
Project: kettle_support_kettle8.0   File: HTTPD.java   View Source Code Vote up 6 votes
/**
 * 获取回复消息
 * 
 * @param con
 * @return
 * @throws IOException
 */
private static String getReceive(HttpURLConnection con) throws IOException {
	InputStream is = null;
	try {
		is = con.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is,
				defaulEncoding));
		StringBuffer sb = new StringBuffer();
		String line;
		while ((line = br.readLine()) != null)
			sb.append(line);
		return sb.toString();
	} finally {
		if (null != is)
			is.close();
	}
}
 
Example 8
Project: iBase4J-Common   File: WebUtil.java   View Source Code Vote up 6 votes
public static <T> T getParameter(HttpServletRequest request, Class<T> cls) {
	String str, wholeStr = "";
	try {
		BufferedReader br = request.getReader();
		while ((str = br.readLine()) != null) {
			wholeStr += str;
		}
		if (StringUtils.isNotBlank(wholeStr)) {
			logger.info("request===>" + wholeStr);
               request.setAttribute("iBase4J.Parameters", wholeStr);
			return InstanceUtil.parse(wholeStr, cls);
		}
	} catch (Exception e) {
		logger.error("", e);
	}
	logger.info("request===>" + JSON.toJSONString(request.getParameterMap()));
	return Request2ModelUtil.covert(cls, request);
}
 
Example 9
Project: incubator-netbeans   File: ProcessUtils.java   View Source Code Vote up 6 votes
private static void readProcessStreamImpl(final InputStream stream, boolean remoteStream,  final LineProcessor lineProcessor) throws IOException {
    if (stream == null) {
        lineProcessor.reset();
        lineProcessor.close();
    } else {
        lineProcessor.reset();
        final BufferedReader br = getReader(stream, remoteStream);
        try {
            String line;
            while ((line = br.readLine()) != null) {
                lineProcessor.processLine(line);
            }
        } finally {
            lineProcessor.close();
            if (br != null) {
                br.close();
            }
        }
    }
}
 
Example 10
Project: phonk   File: FileIO.java   View Source Code Vote up 5 votes
/**
 * Read the contents of the file indicated by fileName
 */
public static String read(InputStream is) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    while (br.ready()) {
        String line = br.readLine();
        sb.append("\n");
        sb.append(line);
    }
    String data = sb.toString();
    return data;
}
 
Example 11
Project: https-github.com-apache-zookeeper   File: GenerateLoad.java   View Source Code Vote up 5 votes
public void run() {
    try {
        System.out.println("Connected to " + s);
        BufferedReader is = new BufferedReader(new InputStreamReader(s
                .getInputStream()));
        String result;
        while ((result = is.readLine()) != null) {
            String timePercentCount[] = result.split(" ");
            if (timePercentCount.length != 5) {
                System.err.println("Got " + result + " from " + s
                        + " exitng.");
                throw new IOException(result);
            }
            long time = Long.parseLong(timePercentCount[0]);
            // int percent = Integer.parseInt(timePercentCount[1]);
            int count = Integer.parseInt(timePercentCount[2]);
            int errs = Integer.parseInt(timePercentCount[3]);
            if (errs > 0) {
                System.out.println(s + " Got an error! " + errs);
            }
            add(time, count, s);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        close();
    }
}
 
Example 12
Project: hadoop   File: TestMiniMRClasspath.java   View Source Code Vote up 5 votes
static String launchWordCount(URI fileSys, JobConf conf, String input,
                              int numMaps, int numReduces) 
throws IOException {
  final Path inDir = new Path("/testing/wc/input");
  final Path outDir = new Path("/testing/wc/output");
  FileSystem fs = FileSystem.get(fileSys, conf);
  configureWordCount(fs, conf, input, numMaps, numReduces, inDir, outDir);
  JobClient.runJob(conf);
  StringBuffer result = new StringBuffer();
  {
    Path[] parents = FileUtil.stat2Paths(fs.listStatus(outDir.getParent()));
    Path[] fileList = FileUtil.stat2Paths(fs.listStatus(outDir,
            new Utils.OutputFileUtils.OutputFilesFilter()));
    for(int i=0; i < fileList.length; ++i) {
      BufferedReader file = 
        new BufferedReader(new InputStreamReader(fs.open(fileList[i])));
      String line = file.readLine();
      while (line != null) {
        result.append(line);
        result.append("\n");
        line = file.readLine();
      }
      file.close();
    }
  }
  return result.toString();
}
 
Example 13
Project: Homework   File: ObjectStreamDemo.java   View Source Code Vote up 5 votes
@SuppressWarnings("resource")
public static void readTxt(String path2) throws Exception
{

	Reader reader = new FileReader(path2);;
	BufferedReader bufr = new BufferedReader(reader);

	StringBuffer buf = new StringBuffer();
	String line = null;
	String s = null;
	int k = 0;
	while ((line = bufr.readLine()) != null)
	{

		if (line.contains("答案"))
		{
			arr1[k] = line;
			line = "aaaaa";
			k++;
		}
		buf.append(line + "\r\n");
	}
	s = buf.toString();
	arr2 = s.split("aaaaa");
	for (int j = 0; j < arr2.length; j++)
	{
		arr[j] = arr2[j];
	}
	bufr.close();
}
 
Example 14
Project: OpenDA   File: UsernamePassword.java   View Source Code Vote up 5 votes
/**
 * Ask a file for the username and password.
 */
private void readFromFile() {
   try {
      FileReader fr = new FileReader(this.credentials);
      BufferedReader br = new BufferedReader(fr);
      this.username = br.readLine();
      this.password = br.readLine();
      br.close();
      fr.close();
   }
   catch (Exception e) {
      this.username = "";
      this.password = "";
   }
}
 
Example 15
Project: Reinickendorf_SER316   File: LoadableProperties.java   View Source Code Vote up 5 votes
private String getNextLine(BufferedReader br) {
    try {
        return br.readLine();
    }
    catch (Exception e) {
        return null;
    }

}
 
Example 16
Project: StackNet   File: PythonGenericClassifier.java   View Source Code Vote up 5 votes
/**
  * 
  * @param confingname : full path and name of the config file
  */
 private void create_light_suprocess(String confingname ) {
  
  // check if file exists
  if (new File(confingname).exists()==false){
   throw new IllegalStateException("Config file does not exist at: " + confingname);
  }
  // create the subprocess
try {

	 String python_path="python";
	 String s_path="lib" + File.separator + "python" + File.separator +  this.script_name.replace(".py", this.index+".py");
	 List<String> list = new ArrayList<String>();
	 list.add(python_path);	
	 list.add(s_path);				 
	 list.add( confingname); 

	 //start the process		 
	 ProcessBuilder p = new ProcessBuilder(list);		  
     p.redirectErrorStream(true);
     Process sp = p.start();
     BufferedReader r = new BufferedReader(new InputStreamReader(sp.getInputStream()));
     String line;
        while(true){
            line = r.readLine();
            if(line == null) { break; }
            if (this.verbose){
            	System.out.println(line);
            }
        }

} catch (IOException e) {
	throw new IllegalStateException(" failed to create sklearn subprocess with config name " + confingname);
}
  
 }
 
Example 17
Project: Moenagade   File: XmlStreamReader.java   View Source Code Vote up 4 votes
/**
 * Returns the encoding declared in the <?xml encoding=...?>, NULL if none.
 *
 * @param is InputStream to create the reader from.
 * @param guessedEnc guessed encoding
 * @return the encoding declared in the <?xml encoding=...?>
 * @throws IOException thrown if there is a problem reading the stream.
 */
private static String getXmlProlog(InputStream is, String guessedEnc)
        throws IOException {
    String encoding = null;
    if (guessedEnc != null) {
        byte[] bytes = new byte[BUFFER_SIZE];
        is.mark(BUFFER_SIZE);
        int offset = 0;
        int max = BUFFER_SIZE;
        int c = is.read(bytes, offset, max);
        int firstGT = -1;
        String xmlProlog = null;
        while (c != -1 && firstGT == -1 && offset < BUFFER_SIZE) {
            offset += c;
            max -= c;
            c = is.read(bytes, offset, max);
            xmlProlog = new String(bytes, 0, offset, guessedEnc);
            firstGT = xmlProlog.indexOf('>');
        }
        if (firstGT == -1) {
            if (c == -1) {
                throw new IOException("Unexpected end of XML stream");
            } else {
                throw new IOException(
                        "XML prolog or ROOT element not found on first "
                                + offset + " bytes");
            }
        }
        int bytesRead = offset;
        if (bytesRead > 0) {
            is.reset();
            BufferedReader bReader = new BufferedReader(new StringReader(
                    xmlProlog.substring(0, firstGT + 1)));
            StringBuffer prolog = new StringBuffer();
            String line = bReader.readLine();
            while (line != null) {
                prolog.append(line);
                line = bReader.readLine();
            }
            Matcher m = ENCODING_PATTERN.matcher(prolog);
            if (m.find()) {
                encoding = m.group(1).toUpperCase();
                encoding = encoding.substring(1, encoding.length() - 1);
            }
        }
    }
    return encoding;
}
 
Example 18
Project: TradingRobot   File: Trading.java   View Source Code Vote up 4 votes
public int buyOrSellAtMarketRate(int unit, double stopLossPrice, String buyOrSell) {
	//statuses: 0: No trade is open 1:There is a trade open already 200: A trade was closed
	int closeTradeStatus = closeExistingTrade(buyOrSell);
	if (closeTradeStatus == 1) return 0;
	if (closeTradeStatus == 200) {
		//Adjust take profit to reflect the loss/profit from the closed trade
		//1 means resend the order
		return 1;
	}
	HttpClientBuilder hcb = HttpClientBuilder.create();
	HttpClient client = hcb.build();
	HttpPost request = new HttpPost(RequestURI.baseURL+"/v3/accounts/"+RequestURI.accountId+"/orders");
	request.addHeader(RequestURI.headerTitle,RequestURI.accessToken);
	request.addHeader("Content-Type", "application/json");
	JSONObject requestOrderObject = new JSONObject();
	JSONObject requestStopLossObject = new JSONObject();
	JSONObject requestObject = new JSONObject();
	requestStopLossObject.put("price", String.valueOf(stopLossPrice));
	requestStopLossObject.put("timeInForce", "GTC");
	requestOrderObject.put("instrument", "EUR_USD");
	requestOrderObject.put("units", (buyOrSell.equals("buy") ? "" : "-")+String.valueOf(unit));
	requestOrderObject.put("timeInForce", "FOK");
	requestOrderObject.put("type", "MARKET");
	requestOrderObject.put("positionFill", "DEFAULT");
	requestOrderObject.put("stopLossOnFill", requestStopLossObject);
	requestObject.put("order", requestOrderObject);
	System.out.println(requestObject.toString());
	try {
		HttpEntity entity = new StringEntity(requestObject.toString());
		request.setEntity(entity);
	} catch (UnsupportedEncodingException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	try {
		HttpResponse response = client.execute(request);
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		JSONObject resultJson = new JSONObject(result.toString());
		System.out.println(resultJson.toString());
		Logger.logString(resultJson.toString());
		return response.getStatusLine().getStatusCode();
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
	return 0;
}
 
Example 19
Project: dubbo2   File: SimpleMonitorService.java   View Source Code Vote up 4 votes
private void appendData(File[] files, Map<String, long[]> data, double[] summary) {
    for (int i = 0; i < files.length; i ++) {
        File file = files[i];
        if (! file.exists()) {
            continue;
        }
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            try {
                int sum = 0;
                int cnt = 0;
                String line;
                while ((line = reader.readLine()) != null) {
                    int index = line.indexOf(" ");
                    if (index > 0) {
                        String key = line.substring(0, index).trim();
                        long value = Long.parseLong(line.substring(index + 1).trim());
                        long[] values = data.get(key);
                        if (values == null) {
                            values = new long[files.length];
                            data.put(key, values);
                        }
                        values[i] += value;
                        summary[0] = Math.max(summary[0], values[i]);
                        summary[1] = summary[1] == 0 ? values[i] : Math.min(summary[1], values[i]);
                        sum += value;
                        cnt ++;
                    }
                }
                if (i == 0) {
                    summary[3] += sum;
                    summary[2] = (summary[2] + (sum / cnt)) / 2;
                }
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
        }
    }
}
 
Example 20
Project: spellcheck   File: SpellChecker.java   View Source Code Vote up 2 votes
public static void main(String[] args) throws IOException, DictionaryBuilderException {
	
	
	DictomatonDictionary dictomatonDictionaryWhitelisted = DictionaryUtil.loadDictionary(DictionaryUtil.loadWhitelist()); 

       BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, Charsets.UTF_8));
       try {
           String word;
           while ((word = reader.readLine()) != null) {
               word = word.trim();
               
               if (word.split("\\s+").length != 1) {
               	
               	System.out.println("Enter one word");

               } else {
               	
               	if (dictomatonDictionaryWhitelisted.suggest(word) == null || dictomatonDictionaryWhitelisted.suggest(word).size() == 0) {
               		
               		if (dictomatonDictionaryWhitelisted.containsOrNot(word) == false) {
               			
               			System.out.print("The word is not in the dictionary, and no suggestion is available");
               			
               		} else {
               			
               			System.out.print(word + " (p = " + dictomatonDictionaryWhitelisted.probability(word) + ")");
               			
               		}
               		
               	} else {
               		
               		
               		Map<String, Double> candidates = new HashMap<String, Double>();
               		
               		for (String candidate : dictomatonDictionaryWhitelisted.suggest(word)) {
               			
               			candidates.put(candidate, dictomatonDictionaryWhitelisted.probability(candidate));
               			
               		}
               		
               		if (dictomatonDictionaryWhitelisted.containsOrNot(word) == true) {
               			
               			candidates.put(word, dictomatonDictionaryWhitelisted.probability(word));
               			
               		}
               		
               		Map<String, Double> result = new LinkedHashMap<>();

               		candidates.entrySet().stream()
                               .sorted(Map.Entry.<String, Double>comparingByValue().reversed())
                               .forEachOrdered(x -> result.put(x.getKey(), x.getValue()));

                       //System.out.println(result);
               		
                       for (String key : result.keySet()) {

                       	System.out.println(key + " (p = " + result.get(key) + ")");
                       	
                       }
                       
               	}
               	
               }

           }
       } catch (IOException e) {
           System.err.println("Error reading from the standard input.");
       } finally {
           try {
               reader.close();
           } catch (IOException ignore) {
           }
       }

	
	
}