Java Code Examples for java.io.BufferedReader

The following are top voted examples for showing how to use java.io.BufferedReader. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: arduino-android   File: WebServer.java View source code Vote up 8 votes
private void handleRequest(BufferedReader input, DataOutputStream output, ResponseHelper helper) throws Exception 
{
 // todo - make bullet proof !!!!!!
  String request = input.readLine(); 
  // GET /page?arg1=fred&arg2=smith HTTP/1.1
  int indexOfSlash = request.indexOf('/');
  int indexOfQ = request.indexOf('?');
  String page = null;
  String paramsString = null;
  String response = "";
  if (indexOfSlash < 0 || indexOfQ <= indexOfSlash)
  {
  	response = generateError("No page specified");
  }
  else 
  {
  	int indexOfSpace = request.indexOf("HTTP")-1;
  	if (indexOfSpace >= indexOfQ)
  	{
  		page = request.substring(indexOfSlash+1, indexOfQ);	   
  		paramsString = request.substring(indexOfQ+1, indexOfSpace); 		
  		response = helper.generateResponse(page, mActivity.URL, parseParams(paramsString));
  	}
  }
  output.writeBytes(constructHttpHeader());
  output.writeBytes(response);
 	 
  output.close();
}
 
Example 2
Project: jena   File: DumpServlet.java View source code Vote up 8 votes
static void printBody(PrintWriter pw, HttpServletRequest req) throws IOException
{
    BufferedReader in = req.getReader() ;
    if ( req.getContentLength() > 0 )
        // Need +2 because last line may not have a CR/LF on it.
        in.mark(req.getContentLength()+2) ;
    else
        // This is a dump - try to do something that works, even if inefficient.
        in.mark(100*1024) ;

    while(true)
    {
        String x = in.readLine() ;
        if ( x == null )
            break ;
        x = x.replaceAll("&", "&amp;") ;
        x = x.replaceAll("<", "&lt;") ;
        x = x.replaceAll(">", "&gt;") ;
        pw.println(x) ;
    }
    try { in.reset() ;} catch (IOException e) { System.out.println("DumpServlet: Reset of content failed: "+e) ; }
}
 
Example 3
Project: iot-server-appliances   File: SidhdhiQuery.java View source code Vote up 7 votes
/**
 * Read sonar data from API URL
 * @param sonarAPIUrl
 * @return
 */
private String readSonarData(String sonarAPIUrl) {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(sonarAPIUrl);
    String responseStr = null;
    try {
        HttpResponse response = client.execute(request);
        log.debug("Response Code : " + response);
        InputStream input = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
        responseStr = String.valueOf(br.readLine());
        br.close();

    } catch (IOException e) {
        //log.error("Exception encountered while trying to make get request.");
        log.error("Error while reading sonar reading from file!");
        return responseStr;
    }
    return responseStr;
}
 
Example 4
Project: iswc2012metadata   File: ToolIO.java View source code Vote up 7 votes
/**
 * pipe stuff to String  (we can just use new String(byte[]) because it uses the heap and may cause outOfMemory exception 
 * 
 * @param inputReader
 * @return
 * @throws Sw4jException
 */
public static String pipeInputStreamToString(InputStream in) throws Sw4jException{
	// TODO: need charset detector if processing non-English stuff
	// we assume default charset
	BufferedReader reader = new BufferedReader(new InputStreamReader(in));
	StringBuffer fileData = new StringBuffer(1000);
	char[] buf = new char[1024];
	int numRead=0;
	try{
		while((numRead=reader.read(buf)) != -1){
			fileData.append(buf, 0, numRead);
		}
		reader.close();
		return fileData.toString();
	} catch (IOException e) {
		Sw4jException e1 = new Sw4jException(Sw4jMessage.STATE_FATAL, e);
		getLogger().error(e1.getMessage());
		throw e1;
	}

}
 
Example 5
Project: mobile-mba-androidapp   File: TestResultsManager.java View source code Vote up 7 votes
private static void verifyReduceSize(File logFile) {
	if (logFile.length() > Constants.SUBMITED_LOGS_MAX_SIZE) {
		File temp = new File(logFile.getAbsolutePath() + "_tmp");
		BufferedReader reader = null;
		FileWriter writer = null;
		try {
			reader = new BufferedReader(new FileReader(logFile));
			reader.skip(logFile.length() - Constants.SUBMITED_LOGS_MAX_SIZE / 2);
			reader.readLine();
			
			writer = new FileWriter(temp);
			IOUtils.copy(reader, writer);
			writer.close();
			reader.close();
			
			logFile.delete();
			temp.renameTo(logFile);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(reader);
			IOUtils.closeQuietly(writer);
		}
	}
}
 
Example 6
Project: h2-bitmap   File: Csv.java View source code Vote up 7 votes
private void initRead() throws IOException {
    if (input == null) {
        try {
            InputStream in = FileUtils.newInputStream(fileName);
            in = new BufferedInputStream(in, Constants.IO_BUFFER_SIZE);
            input = new InputStreamReader(in, characterSet);
        } catch (IOException e) {
            close();
            throw e;
        }
    }
    if (!input.markSupported()) {
        input = new BufferedReader(input);
    }
    input.mark(1);
    int bom = input.read();
    if (bom != 0xfeff) {
        // Microsoft Excel compatibility
        // ignore pseudo-BOM
        input.reset();
    }
    inputBuffer = new char[Constants.IO_BUFFER_SIZE * 2];
    if (columnNames == null) {
        readHeader();
    }
}
 
Example 7
Project: ArubaSyslog   File: PPEFilter.java View source code Vote up 5 votes
public static void main(String[] args) throws IOException{
	
   	// Initial options
       String input_file_location = "";
       String output_file_location = "";
       
       // fetch command line options 
       int optSetting = 0;  
       for (; optSetting < args.length; optSetting++) {  
           if ("-i".equals(args[optSetting])) {  
               input_file_location = args[++optSetting];  
           } else if ("-o".equals(args[optSetting])) {  
               output_file_location = args[++optSetting];  
           }
       }

       if(input_file_location.length() == 0 || output_file_location.length() == 0) {
           System.out.println("Usage: PPEFilter -i <source> -o <destination>");
           System.exit(-1);
       }
       
       // prepare for reading files one by one
 		File input_folder = null;  
 		input_folder = new File(input_file_location);  
 		File[] files = input_folder.listFiles(); 
 		
 		// String input_file_path = "";
 		String uid = "";
 		String input_file_name = "";
 		String output_file = "";
 		
 		// Skip invalid files without name format \d+.mv
 		String filename_regex = "[\\d\\w.]+.mv$";
 		Pattern p = Pattern.compile(filename_regex);
 		Matcher m = null;
	
 		for (File input_file : files) {
 			
 			// extract input_file_name as output_file_name
 			// input_file_path = input_file.getAbsolutePath();
 		    input_file_name = input_file.getName();
 		    
 		    // Skip invalid files without name format \d+.mv
 		    m = p.matcher(input_file_name);
 		    if ( m.find() == false)
 		    	continue;
 		    
 		    uid = input_file_name.split("\\.")[0];
 		    output_file = output_file_location + uid;
 		    
 		    // Input stream
 			FileReader ifr = new FileReader(input_file);
 			BufferedReader ibr = new BufferedReader(ifr);
 			
 			// Create parent directories if they are not available.
 			File output_folder = new File(output_file_location);
 			if ( !output_folder.exists() )
 				output_folder.mkdirs();
 			
 			// Output stream
 			File file = new File(output_file);	
           if(!file.exists()) {
               if(!file.createNewFile()) {
               	System.out.println("Can't create file.");
               }
           }
           
 			FileWriter ofr = new FileWriter(file);
 			BufferedWriter obr = new BufferedWriter(ofr);
 			
 			// Processing one file for a user
 			String line ="";
 			String [] ap_info;
 			ConvSession cs = null;
 			
 			while ((line = ibr.readLine()) != null) {
			
 				line = line.replaceAll("[\\n\\r]*","");
 				
 				// Read the conversation sessions
 				// Each session ends with "OFF" flag.
 				// Each file will be split into sessions as 
 				// count of "OFF"'s
 				if ( cs == null )
 					cs = new ConvSession(uid);
			ap_info = line.split("\\t");
			
			if ( ap_info[1].equals("OFF") == false && ibr.ready() == true) {
				// If the last line is without OFF
				// Add a fake OFF signs to the session records
				cs.addRecord(Long.parseLong(ap_info[0]), ap_info[1]);
				continue;
			}
			cs.addRecord(Long.parseLong(ap_info[0]), "OFF");
			
			// Filter the Ping-Pong Effect on the basis of each session,
			// and write the new session into an output file.
			List<APRecord> final_records = cs.removePingPongEffect();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			TimeZone tz = TimeZone.getTimeZone("GMT-04:00");	//New York timezone
			df.setTimeZone(tz);
			
			for ( APRecord r : final_records) {
				Date start = new Date(r.start_time*1000);
				Date end = new Date((r.start_time+r.duration)*1000);
				obr.write(r.name+"\t"+df.format(start)+"\t"+r.duration+"\t"+df.format(end)+"\n");
				//System.out.println(r.name+"\t"+r.start_time+"\t"+r.duration);
			}
			//obr.write("OFF\n");
			
			// Reset to start a new session
			cs = null;
 			}
		
 			ibr.close();
 			ifr.close();
		obr.close();
		ofr.close();
 		}
}