Java Code Examples for java.io.BufferedReader#readLine()
The following examples show how to use
java.io.BufferedReader#readLine() .
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: Install.java From Lottery with GNU General Public License v2.0 | 6 votes |
/** * 读取sql语句。“/*”开头为注释,“;”为sql结束。 * * @param fileName * sql文件地址 * @return list of sql * @throws Exception */ public static List<String> readSql(String fileName) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(fileName), UTF8)); List<String> sqlList = new ArrayList<String>(); StringBuilder sqlSb = new StringBuilder(); String s = ""; while ((s = br.readLine()) != null) { if (s.startsWith("/*") || s.startsWith("#") || StringUtils.isBlank(s)) { continue; } if (s.endsWith(";")) { sqlSb.append(s); sqlSb.setLength(sqlSb.length() - 1); sqlList.add(sqlSb.toString()); sqlSb.setLength(0); } else { sqlSb.append(s); } } br.close(); return sqlList; }
Example 2
Source File: JSensorsTest.java From jSensors with Apache License 2.0 | 6 votes |
private JSensors getJSensorsStub(String testset) throws IOException { Map<String, String> config = new HashMap<String, String>(); config.put("testMode", "STUB"); InputStream is = JSensorsTest.class.getClassLoader().getResourceAsStream(testset); BufferedReader br = new BufferedReader(new InputStreamReader(is)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } config.put("stubContent", sb.toString()); } finally { br.close(); } return JSensors.get.config(config); }
Example 3
Source File: Uploader.java From jpexs-decompiler with GNU General Public License v3.0 | 6 votes |
/** * Completes the request and receives response from the server. * * @return a list of Strings as response in case the server returned * status OK, otherwise an exception is thrown. * @throws IOException */ public boolean finish(List<String> response) throws IOException { response.clear(); //writer.append(LINE_FEED).flush(); writer.append("--" + boundary + "--").append(LINE_FEED); writer.close(); // checks server's status code first int status = httpConn.getResponseCode(); BufferedReader reader = new BufferedReader(new InputStreamReader( httpConn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { response.add(line); } reader.close(); httpConn.disconnect(); return status == HttpURLConnection.HTTP_OK; }
Example 4
Source File: UtilFile.java From apidiff with MIT License | 6 votes |
/** * Converting a CSV file to a list of maps. The separator is ";". * The first line defines the header. * The first column defines the map key. * * CSV: * nameproject;URL; * aserg-ufmg/apidiff;https://github.com/aserg-ufmg/apidiff.git * aserg-ufmg/RefDiff;https://github.com/aserg-ufmg/RefDiff.git * * Output: * [ * {namepProject=aserg-ufmg/apidiff, URL=https://github.com/aserg-ufmg/apidiff.git}, * {namepProject=aserg-ufmg/RefDiff, URL=https://github.com/aserg-ufmg/RefDiff.git} * ] * * @param fileName - File name (i.e., "output.csv") * @return - list of maps * @throws IOException - Exception for file operations */ public static List<Map<String, String>> convertCSVFileToListofMaps(final String fileName) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(fileName)); String SEPARATOR = ";"; String line = ""; List<Map<String, String>> result = new ArrayList<Map<String, String>>(); try { String[] header = br.readLine().split(SEPARATOR); while ((line = br.readLine()) != null){ String [] data = line.split(SEPARATOR); Map<String, String> value = new HashMap<String, String>(); for(int i = 0; i < data.length; i++){ value.put(header[i], data[i]); } result.add(value); } } finally { br.close(); } return result; }
Example 5
Source File: JKULFMProcessor.java From TagRec with GNU Affero General Public License v3.0 | 6 votes |
private static List<String> getFilterLines(Set<String> filterUsers) throws Exception { String filePath = EVENTS_FILE; List<String> filterLines = new ArrayList<String>(); InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(filePath)), "UTF8"); BufferedReader br = new BufferedReader(reader); String line = null; int i = 0; while ((line = br.readLine()) != null) { String userID = line.substring(0, line.indexOf('\t')); if (filterUsers.contains(userID)) { filterLines.add(line); i++; } } System.out.println("Number of lines: " + i); br.close(); reader.close(); return filterLines; }
Example 6
Source File: TranslationResources.java From ermaster-b with Apache License 2.0 | 6 votes |
private void load(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { int index = line.indexOf(","); if (index == -1 || index == line.length() - 1) { continue; } String key = line.substring(0, index).trim(); if ("".equals(key)) { continue; } String value = line.substring(index + 1).trim(); this.translationMap.put(key, value); key = key.replaceAll("[aiueo]", ""); if (key.length() > 1) { this.translationMap.put(key, value); } } }
Example 7
Source File: ClassPathResourceTest.java From deeplearning4j with Apache License 2.0 | 6 votes |
@Test public void testInputStreamSlash() throws Exception { ClassPathResource resource = new ClassPathResource("datavec-api/csvsequence_1.txt"); File intFile = resource.getFile(); if (isWindows) { assertThat(intFile.length(), anyOf(equalTo(60L), equalTo(64L))); } else { assertEquals(60, intFile.length()); } InputStream stream = resource.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line = ""; int cnt = 0; while ((line = reader.readLine()) != null) { cnt++; } assertEquals(5, cnt); }
Example 8
Source File: StreamingCommandUtils.java From spork with Apache License 2.0 | 6 votes |
/** * @return a non-null String as per {@link CacheLoader}'s Javadoc. * {@link StreamingCommand#addPathToShip(String)} will check * that this String is a path to a valid file, so we won't check * that again here. */ public String load(String file) { try { String utility = "which"; if (System.getProperty("os.name").toUpperCase().startsWith("WINDOWS")) { utility = "where"; } ProcessBuilder processBuilder = new ProcessBuilder(new String[] {utility, file}); Process process = processBuilder.start(); BufferedReader stdout = new BufferedReader(new InputStreamReader(process.getInputStream())); String fullPath = stdout.readLine(); return (process.waitFor() == 0 && fullPath != null) ? fullPath : ""; } catch (Exception e) {} return ""; }
Example 9
Source File: Documentation.java From symja_android_library with GNU General Public License v3.0 | 5 votes |
/** * Load the documentation from resource folder if available and print to output. * * @param symbolName */ public static boolean printDocumentation(Appendable out, String symbolName) { // read markdown file String fileName = symbolName + ".md"; // Get file from resources folder ClassLoader classloader = Thread.currentThread().getContextClassLoader(); try { InputStream is = classloader.getResourceAsStream(fileName); if (is != null) { final BufferedReader f = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; boolean emptyLine = false; while ((line = f.readLine()) != null) { if (line.startsWith("```")) { continue; } if (line.trim().length() == 0) { if (emptyLine) { continue; } emptyLine = true; } else { emptyLine = false; } out.append(line); out.append("\n"); } f.close(); is.close(); return true; } } catch (IOException e) { e.printStackTrace(); } return false; }
Example 10
Source File: MainActivity.java From Notepad with Apache License 2.0 | 5 votes |
@Override public String loadNoteTitle(String filename) throws IOException { // Open the file on disk FileInputStream input = openFileInput(filename); InputStreamReader reader = new InputStreamReader(input); BufferedReader buffer = new BufferedReader(reader); // Load the file String line = buffer.readLine(); // Close file on disk reader.close(); return(line); }
Example 11
Source File: Utils.java From candybean with GNU Affero General Public License v3.0 | 5 votes |
/** * Executes a forked process that runs some given command string. Prints the output of the command execution to console. * * @param cmd * @throws IOException */ public static void run(String cmd) throws IOException { Process process = new ProcessBuilder(cmd).start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine(); log.info("Run command: " + cmd); while (line != null) { log.info(line); line = reader.readLine(); } }
Example 12
Source File: FilterNewLines.java From semafor-semantic-parser with GNU General Public License v3.0 | 5 votes |
public static void main(String[] args) throws Exception { String root = "/usr2/dipanjan/experiments/FramenetParsing/FrameStructureExtraction/mstscripts/data"; String[] infiles = {"semeval.fulltrain.berkeley.parsed", "semeval.fulldev.berkeley.parsed", "semeval.fulltest.berkeley.parsed"}; String[] outfiles = {"semeval.fulltrain.berkeley.parsed.trimmed", "semeval.fulldev.berkeley.parsed.trimmed", "semeval.fulltest.berkeley.parsed.trimmed"}; for(int i = 0; i < 3; i ++) { BufferedReader bReader = new BufferedReader(new FileReader(root+"/"+infiles[i])); BufferedWriter bWriter = new BufferedWriter(new FileWriter(root+"/"+outfiles[i])); String line = null; int count=0; while((line=bReader.readLine())!=null) { line=line.trim(); if(!line.equals("")) bWriter.write(line+"\n"); if(count%1000==0) System.out.print(count+" "); if(count%10000==0) System.out.println(); count++; } bReader.close(); bWriter.close(); } }
Example 13
Source File: Main.java From dependensee with GNU General Public License v2.0 | 5 votes |
public static void writeFromCONLLFile(String infile, String outfile) throws Exception { Graph g = new Graph(); BufferedReader input = new BufferedReader(new FileReader(infile)); String line = null; List<Edge> tempEdges = new ArrayList<Edge>(); while ((line = input.readLine()) != null) { if ("".equals(line)) break; // stop at sentence boundary if (line.startsWith("#")) continue; // skip comments String[] parts = line.split("\\s+"); if (!parts[0].matches("^-?\\d+$")) continue; //skip ranges g.addNode(parts[1],Integer.parseInt(parts[0]),parts[2]); tempEdges.add( new Edge( Integer.parseInt(parts[6])-1, Integer.parseInt(parts[0])-1, parts[7])); } for (Edge e: tempEdges ) { if (e.sourceIndex==-1 ) { g.setRoot(e.sourceIndex); continue; } g.addEdge(g.nodes.get(e.sourceIndex), g.nodes.get(e.targetIndex),e.label); } BufferedImage image = Main.createTextImage(g,1); ImageIO.write(image, "png", new File(outfile)); }
Example 14
Source File: CustomAppKeyTest.java From YiBo with Apache License 2.0 | 5 votes |
@Test public void testOauth1CustomeAppKey() { Authorization auth = new Authorization(Config.SP); OAuthConfig oauthConfig = auth.getoAuthConfig(); oauthConfig.setConsumerKey(Config.appkey); oauthConfig.setConsumerSecret(Config.appSecret); oauthConfig.setCallbackUrl(Config.callbackUrl); try { OAuthAuthorizeHelper oauthHelper = new OAuthAuthorizeHelper(); auth = oauthHelper.retrieveRequestToken(auth); String authorizeUrl = oauthHelper.getAuthorizeUrl(auth); BareBonesBrowserLaunch.openURL(authorizeUrl); String verifier = null; while (null == verifier || verifier.trim().length() == 0) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please Enter verifier : "); verifier = br.readLine(); } auth = oauthHelper.retrieveAccessToken(auth, verifier.trim()); } catch (Exception e) { e.printStackTrace(); auth = null; } assertNotNull(auth); }
Example 15
Source File: AbstractServerTest.java From barefoot with Apache License 2.0 | 4 votes |
@Test public void ReponseSuccessTest() throws InterruptedException, UnknownHostException, IOException { final TestServer server = new TestServer(TestServer.createServerProperty(12345, 200, 400, 2), true); Thread thread = new Thread() { @Override public void run() { server.runServer(); } }; int workTime = 200; // Start server thread.start(); Thread.sleep(200); // Connect to server Socket client = new Socket(InetAddress.getLocalHost(), 12345); // Send request PrintWriter writer = new PrintWriter(client.getOutputStream()); writer.println(workTime); writer.flush(); Thread.sleep(workTime + 100); // Receive response BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream())); String rescode = reader.readLine(); String response = reader.readLine(); // Close connection writer.close(); reader.close(); client.close(); // Stop server server.stopServer(); thread.join(100); assertEquals("SUCCESS", rescode); assertEquals("work " + workTime + " ms", response); }
Example 16
Source File: 00947 Master Mind Helper.java From UVA with GNU General Public License v3.0 | 4 votes |
public static void main (String[]args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //pre-generate numbers. int [][][] numbers=new int [6][60000][6]; //9^5 max int [] numbersCount=new int [6]; numbers[1]=new int [][] {new int [] {1},new int [] {2},new int [] {3},new int [] {4},new int [] {5},new int [] {6},new int [] {7},new int [] {8},new int [] {9}}; numbersCount[1]=numbers[1].length; for (int i=2;i<numbers.length;i++) { for (int i2=0;i2<numbersCount[i-1];i2++) { for (int i3=1;i3<10;i3++) { numbers[i][numbersCount[i]]=Arrays.copyOf(numbers[i-1][i2], i); numbers[i][numbersCount[i]][i-1]=i3; numbersCount[i]++; } } } int testCaseCount=Integer.parseInt(br.readLine()); for (int testCase=0;testCase<testCaseCount;testCase++) { StringTokenizer st=new StringTokenizer(br.readLine()); int input=Integer.parseInt(st.nextToken()); int reqStrongCount=Integer.parseInt(st.nextToken()); int reqWeakCount=Integer.parseInt(st.nextToken()); int inputLength=(int)Math.log10(input)+1; int [] inputAry=new int [inputLength]; for (int i=inputAry.length-1;i>=0;i--) { inputAry[i]=input%10; input/=10; } boolean [] inputFlag=new boolean [inputLength]; boolean [] checkFlag=new boolean [inputLength]; int currStrongCount=0; int currWeakCount=0; int count=0; for (int i=0;i<numbersCount[inputLength];i++) { currStrongCount=0; currWeakCount=0; Arrays.fill(inputFlag,false); Arrays.fill(checkFlag,false); for (int i2=0;i2<inputLength;i2++) { if (inputAry[i2]==numbers[inputLength][i][i2]) { currStrongCount++; inputFlag[i2]=true; checkFlag[i2]=true; } } for (int i2=0;i2<inputLength;i2++) { if (!inputFlag[i2]) { for (int i3=0;i3<inputLength;i3++) { if (!checkFlag[i3] && inputAry[i2]==numbers[inputLength][i][i3]) { currWeakCount++; inputFlag[i2]=true; checkFlag[i3]=true; break; } } } } if (currStrongCount==reqStrongCount && currWeakCount==reqWeakCount) { count++; } } System.out.println(count); } }
Example 17
Source File: SQLService.java From odo with Apache License 2.0 | 4 votes |
/** * Update database schema * * @param migrationPath path to migrations */ public void updateSchema(String migrationPath) { try { logger.info("Updating schema... "); int current_version = 0; // first check the current schema version HashMap<String, Object> configuration = getFirstResult("SELECT * FROM " + Constants.DB_TABLE_CONFIGURATION + " WHERE " + Constants.DB_TABLE_CONFIGURATION_NAME + " = \'" + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + "\'"); if (configuration == null) { logger.info("Creating configuration table.."); // create configuration table executeUpdate("CREATE TABLE " + Constants.DB_TABLE_CONFIGURATION + " (" + Constants.GENERIC_ID + " INTEGER IDENTITY," + Constants.DB_TABLE_CONFIGURATION_NAME + " VARCHAR(256)," + Constants.DB_TABLE_CONFIGURATION_VALUE + " VARCHAR(1024));"); executeUpdate("INSERT INTO " + Constants.DB_TABLE_CONFIGURATION + "(" + Constants.DB_TABLE_CONFIGURATION_NAME + "," + Constants.DB_TABLE_CONFIGURATION_VALUE + ")" + " VALUES (\'" + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + "\', '0');"); } else { logger.info("Getting current schema version.."); // get current version current_version = new Integer(configuration.get("VALUE").toString()); logger.info("Current schema version is {}", current_version); } // loop through until we get up to the right schema version while (current_version < Constants.DB_CURRENT_SCHEMA_VERSION) { current_version++; // look for a schema file for this version logger.info("Updating to schema version {}", current_version); String currentFile = migrationPath + "/schema." + current_version; Resource migFile = new ClassPathResource(currentFile); BufferedReader in = new BufferedReader(new InputStreamReader( migFile.getInputStream())); String str; while ((str = in.readLine()) != null) { // execute each line if (str.length() > 0) { executeUpdate(str); } } in.close(); } // update the configuration table with the correct version executeUpdate("UPDATE " + Constants.DB_TABLE_CONFIGURATION + " SET " + Constants.DB_TABLE_CONFIGURATION_VALUE + "='" + current_version + "' WHERE " + Constants.DB_TABLE_CONFIGURATION_NAME + "='" + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + "';"); } catch (Exception e) { logger.info("Error in executeUpdate"); e.printStackTrace(); } }
Example 18
Source File: HttpPostGet.java From bidder with Apache License 2.0 | 4 votes |
/** * Send an HTTP get, once the http url is defined. * * @param url * . The url string to send. * @return String. The HTTP response to the GET * @throws Exception * on network errors. */ public String sendGet(String url, int connTimeout, int readTimeout) throws Exception { URL obj = new URL(url); http = (HttpURLConnection) obj.openConnection(); http.setConnectTimeout(connTimeout); http.setReadTimeout(readTimeout); http.setRequestProperty("Connection", "keep-alive"); // optional default is GET http.setRequestMethod("GET"); // add request header http.setRequestProperty("User-Agent", USER_AGENT); int responseCode = http.getResponseCode(); // System.out.println("\nSending 'GET' request to URL : " + url); // System.out.println("Response Code : " + responseCode); String value = http.getHeaderField("Content-Encoding"); if (value != null && value.equals("gzip")) { byte bytes [] = new byte[4096]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPInputStream gis = new GZIPInputStream(http.getInputStream()); while(true) { int n = gis.read(bytes); if (n < 0) break; baos.write(bytes,0,n); } return new String(baos.toByteArray()); } BufferedReader in = new BufferedReader(new InputStreamReader( http.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); }
Example 19
Source File: SnapclientService.java From snapdroid with GNU General Public License v3.0 | 4 votes |
private void startProcess() throws IOException { Log.d(TAG, "startProcess"); String player = "oboe"; String configuredEngine = Settings.getInstance(getApplicationContext()).getAudioEngine(); if (configuredEngine.equals("OpenSL")) player = "opensl"; else if (configuredEngine.equals("Oboe")) player = "oboe"; else { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) player = "opensl"; else player = "oboe"; } String rate = null; String fpb = null; String sampleformat = "*:16:*"; AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE); if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) && Settings.getInstance(getApplicationContext()).doResample()) { rate = audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE); fpb = audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER); sampleformat = rate + ":16:*"; } Log.i(TAG, "Configured engine: " + configuredEngine + ", active engine: " + player + ", sampleformat: " + sampleformat); ProcessBuilder pb = new ProcessBuilder() .command(this.getApplicationInfo().nativeLibraryDir + "/libsnapclient.so", "-h", host, "-p", Integer.toString(port), "--hostID", getUniqueId(this.getApplicationContext()), "--player", player, "--sampleformat", sampleformat, "--logfilter", "*:info,Stats:debug") .redirectErrorStream(true); Map<String, String> env = pb.environment(); if (rate != null) env.put("SAMPLE_RATE", rate); if (fpb != null) env.put("FRAMES_PER_BUFFER", fpb); process = pb.start(); Thread reader = new Thread(new Runnable() { @Override public void run() { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); String line; try { while ((line = bufferedReader.readLine()) != null) { log(line); } } catch (IOException e) { e.printStackTrace(); } } }); logReceived = false; reader.start(); }
Example 20
Source File: MiscellaneousCommands.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
Result mergeLogs(List<String> logsToMerge) { //create a new process for merging LogWrapper.getInstance().fine("Exporting logs merging logs" + logsToMerge.size()); if (logsToMerge.size() > 1){ List<String> commandList = new ArrayList<String>(); commandList.add(System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar + "java"); commandList.add("-classpath"); commandList.add(System.getProperty("java.class.path", ".")); commandList.add(MergeLogs.class.getName()); commandList.add(logsToMerge.get(0).substring(0,logsToMerge.get(0).lastIndexOf(File.separator) + 1)); ProcessBuilder procBuilder = new ProcessBuilder(commandList); StringBuilder output = new StringBuilder(); String errorString = new String(); try { LogWrapper.getInstance().fine("Exporting logs now merging logs"); Process mergeProcess = procBuilder.redirectErrorStream(true) .start(); mergeProcess.waitFor(); InputStream inputStream = mergeProcess.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader( inputStream)); String line = null; while ((line = br.readLine()) != null) { output.append(line).append(GfshParser.LINE_SEPARATOR); } mergeProcess.destroy(); } catch (Exception e) { LogWrapper.getInstance().fine(e.getMessage()); return ResultBuilder.createUserErrorResult(CliStrings.EXPORT_LOGS__MSG__FUNCTION_EXCEPTION + "Could not merge" ) ; } finally { if (errorString != null) { output.append(errorString).append(GfshParser.LINE_SEPARATOR); LogWrapper.getInstance().fine("Exporting logs after merging logs "+output); } } if (output.toString().contains("Sucessfully merged logs")){ LogWrapper.getInstance().fine("Exporting logs Sucessfully merged logs"); return ResultBuilder.createInfoResult("Successfully merged"); }else{ LogWrapper.getInstance().fine("Could not merge"); return ResultBuilder.createUserErrorResult(CliStrings.EXPORT_LOGS__MSG__FUNCTION_EXCEPTION + "Could not merge") ; } } return ResultBuilder.createInfoResult("Only one log file, nothing to merge"); }