public String getQueryByRowID(int rowID, String pno) { String filePath = SysConfig.Catalog_Project + "pipeline/" + pno + "/workload.txt"; String query = null; try (BufferedReader reader = InputFactory.Instance().getReader(filePath)) { String line = reader.readLine(); String[] splits; int i = 0; while ((line = reader.readLine()) != null) { if (i == rowID) { splits = line.split("\t"); query = splits[2]; break; } i++; } } catch (IOException e) { e.printStackTrace(); } return query; }
public void runCMD(String command) throws Exception { Process p = Runtime.getRuntime().exec("cmd /c cmd.exe /c " + command + " exit");//cmd /c dir 执行完dir命令后关闭窗口。 //runCMD_bat("C:\\1.bat");/调用 //Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe /c " + path + " exit");//显示窗口 打开一个新窗口后执行dir指令(原窗口会关闭) BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String readLine = br.readLine(); while (readLine != null) { readLine = br.readLine(); System.out.println(readLine); } if (br != null) { br.close(); } p.destroy(); p = null; }
public static void main(String ... ags)throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); StringTokenizer tk = new StringTokenizer(in.readLine()); TreeSet<Integer> ts = new TreeSet<>(); for(int i=0;i<n;i++) { int val = Integer.parseInt(tk.nextToken()); if(val%2 != 0) ts.add(i); } if(ts.size()%2 != 0) System.out.println("NO"); else { int res = 0; while(ts.size() != 0) { int a = ts.pollFirst(); int b = ts.pollFirst(); res += (b-a-1)*2 + 2; } System.out.println(res); } }
public static String getURL(String surl) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); System.setProperty("java.net.preferIPv4Addresses", "true"); System.setProperty("java.net.preferIPv6Addresses", "false"); System.setProperty("validated.ipv6", "false"); String fullString = ""; try { URL url = new URL(surl); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { fullString += line; } reader.close(); } catch (Exception ex) { //showDialog("Verbindungsfehler.",parent); } return fullString; }
private void doPostRequest(String destination, String parms) throws IOException { URL url = new URL(destination); String response = ""; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(parms); writer.flush(); writer.close(); os.close(); conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { String line; BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line=br.readLine()) != null) { response+=line; } } else { response=""; } }
private static void process(String urlstring) { try { URL url = new URL(urlstring); System.out.println("Connecting to " + url); URLConnection connection = url.openConnection(); connection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader( connection.getInputStream())); for(String line; (line = in.readLine()) != null; ) if (line.startsWith(MARKER)) { System.out.println(TAG.matcher(line).replaceAll("")); } in.close(); } catch (IOException ioe) { System.err.println("" + ioe); } }
public static String decompress(byte[] compressed) { if(compressed==null) return null; ByteArrayInputStream bis = new ByteArrayInputStream(compressed); try { GZIPInputStream gis = new GZIPInputStream(bis); BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8")); StringBuilder sb = new StringBuilder(); String line; while((line = br.readLine()) != null) { sb.append(line); } br.close(); gis.close(); bis.close(); return sb.toString(); }catch (IOException ex){ ex.printStackTrace(); } return null; }
private java.util.HashMap loadBlacklist() { java.util.HashMap<String,String> map = new java.util.HashMap<String,String>(); try { java.io.BufferedReader input = new java.io.BufferedReader( new java.io.FileReader( BLACKLISTFILE ) ); java.lang.String line = ""; while ((line = input.readLine()) != null) { if (false) { map.put( line, line ); } } input.close(); } catch ( java.io.IOException e ) { System.out.println( "File is not found" ); } return map; }
private java.util.HashMap loadBlacklist() { java.util.HashMap<String,String> map = new java.util.HashMap<String,String>(); try { java.io.BufferedReader input = new java.io.BufferedReader( new java.io.FileReader( BLACKLISTFILE ) ); java.lang.String line = ""; while ((line = input.readLine()) != null) { if (line.length() > 7) { map.put( line, line ); } } input.close(); } catch ( java.io.IOException e ) { System.out.println( "File is not found" ); } return map; }
private void initConfig() throws IOException { // generate temporary files tmpDir = createTempDirectory(); ClassLoader classLoader = EmbeddedCassandraService.class.getClassLoader(); InputStream in = getClass().getResourceAsStream("/cassandra.yaml"); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); File tmp = new File(tmpDir.getAbsolutePath() + File.separator + "cassandra.yaml"); // Assert.assertTrue(tmp.createNewFile()); BufferedWriter b = new BufferedWriter(new FileWriter(tmp)); //copy cassandra.yaml; inject absolute paths into cassandra.yaml String line; while ((line = reader.readLine()) != null) { line = line.replace("$PATH", "'" + tmp.getParentFile()); b.write(line + "\n"); b.flush(); } // Tell cassandra where the configuration files are. // Use the test configuration file. System.setProperty(CAS_CONFIG_PROP, tmp.getAbsoluteFile().toURI().toString()); LOG.info("Embedded Cassasndra config generated at [{}]", System.getProperty(CAS_CONFIG_PROP)); }
public static void main(String[] args) throws Exception { //напишите тут ваш код BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int i = 0; int count = 0; double sum = 0; while (i != -1) { i = Integer.parseInt(br.readLine()); sum += i; count++; } double avg = (sum+1) / (count-1); System.out.println(avg); }
private static List<String> getNotCommentedLines(InputStream excludedClassesStream) { List<String> list = new ArrayList<>(); try(BufferedReader br = new BufferedReader(new InputStreamReader(excludedClassesStream))){ String line; while ((line = br.readLine()) != null) { String element = line.trim(); if(! element.startsWith("//") && !element.isEmpty()) { list.add(element); } } } catch(IOException e) { throw new RuntimeException(e); } return Collections.unmodifiableList(list); }
/** * 得到响应对象 * * @param urlConnection * @return 响应对象 * @throws IOException */ private HttpRespons makeContent(String urlString, HttpURLConnection urlConnection) throws IOException { HttpRespons httpResponser = new HttpRespons(); try { InputStream in = urlConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, Charset.forName(this.defaultContentEncoding))); httpResponser.contentCollection = new Vector<String>(); StringBuffer temp = new StringBuffer(); String line = bufferedReader.readLine(); while (line != null) { httpResponser.contentCollection.add(line); temp.append(line).append(""); line = bufferedReader.readLine(); } bufferedReader.close(); String ecod = urlConnection.getContentEncoding(); if (ecod == null) ecod = this.defaultContentEncoding; httpResponser.urlString = urlString; httpResponser.defaultPort = urlConnection.getURL().getDefaultPort(); httpResponser.file = urlConnection.getURL().getFile(); httpResponser.host = urlConnection.getURL().getHost(); httpResponser.path = urlConnection.getURL().getPath(); httpResponser.port = urlConnection.getURL().getPort(); httpResponser.protocol = urlConnection.getURL().getProtocol(); httpResponser.query = urlConnection.getURL().getQuery(); httpResponser.ref = urlConnection.getURL().getRef(); httpResponser.userInfo = urlConnection.getURL().getUserInfo(); httpResponser.content = temp.toString(); httpResponser.contentEncoding = ecod; httpResponser.code = urlConnection.getResponseCode(); httpResponser.message = urlConnection.getResponseMessage(); httpResponser.contentType = urlConnection.getContentType(); httpResponser.method = urlConnection.getRequestMethod(); httpResponser.connectTimeout = urlConnection.getConnectTimeout(); httpResponser.readTimeout = urlConnection.getReadTimeout(); return httpResponser; } catch (IOException e) { throw e; } finally { if (urlConnection != null) urlConnection.disconnect(); } }
/** * Reads in all the edges from the BRITE file and adds them to the given graph. * The required nodes have to present in the given graph. * * @param graph graph to add the edges to * @param reader reader at the position to start * @throws IOException in case of an I/O error */ private static void extractEdges(Graph graph, BufferedReader reader) throws IOException { String line = reader.readLine(); while (line != null && !line.isEmpty()) { // split the line into pieces and parse them separately String[] values = line.split("\t"); if (values.length >= 9) { int id = Integer.parseInt(values[0]); int from = Integer.parseInt(values[1]); int to = Integer.parseInt(values[2]); float delay = Float.parseFloat(values[4]); float bandwidth = Float.parseFloat(values[5]); // get the source and destination nodes from the existing graph Router fromNode = graph.getRouter(from); Router toNode = graph.getRouter(to); if (fromNode != null && toNode != null) { // create the new edge object graph.createEdge(id, fromNode, toNode, delay, bandwidth); } } line = reader.readLine(); } }
public static boolean sessionAlreadyImported(File xmlImportFile, File xmlSessionFile) throws IOException { BufferedReader br1 = new BufferedReader(new FileReader(xmlSessionFile)); //sessionfile BufferedReader br2 = new BufferedReader(new FileReader(xmlImportFile)); //desktop import String s1, s2; s1 = br1.readLine(); s2 = br2.readLine(); s2 = br2.readLine(); br2.mark(2000);; while(s1 != null) { while (s1 != null && s2 != null && s1.equals(s2)) { s1 = br1.readLine(); s2 = br2.readLine(); if (s2 == null) { br1.close(); br2.close(); return true; } } br2.reset(); s1 = br1.readLine(); } br1.close(); br2.close(); return false; }
protected static java.util.List<GenomeLoc> getRealignerTargetIntervalValue(String filePath, RefContigInfo refContigInfo) { String intervalFilePath = TestRealignerTargetCreator.class.getResource(filePath).getFile(); java.util.List<GenomeLoc> result = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(new File(intervalFilePath)))) { String line = reader.readLine(); while (line != null) { if (line.length() > 0) { String[] split1 = line.split(":"); String contigName = split1[0]; int contigId = refContigInfo.getId(contigName); String[] split2 = split1[1].split("-"); int start = Integer.parseInt(split2[0]); int end = (split2.length == 1) ? start : Integer.parseInt(split2[1]); result.add(new GenomeLoc(contigName, contigId, start, end)); } line = reader.readLine(); } } catch (Exception e) { e.printStackTrace(); } return result; }
private void print_content(HttpsURLConnection con){ ObjectMapper mapper = new ObjectMapper(); if(con!=null){ try { System.out.println("****** Content of the URL ********"); BufferedReader br = new BufferedReader( new InputStreamReader(con.getInputStream())); String input; while ((input = br.readLine()) != null){ if(!input.matches("Content")) { WrapperCb w = mapper.readValue(input, WrapperCb.class); System.out.println(w.getData().getRates().getUsd()); } System.out.println(input); } br.close(); } catch (IOException e) { e.printStackTrace(); } } }
protected String doInBackground(final Date... dates) { final StringBuilder formattedText = new StringBuilder(); formattedText.append("<h1>").append(DateFormat.getDateInstance().format(dates[0])).append("</h1>"); try { final URL url = new URL(baseUrl + "/" + df.format(dates[0]) + ".txt"); Log.i("RetrieveLogTask", "Loading " + url); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; do { line = reader.readLine(); if (line != null) { appendFormatted(formattedText, line); } } while (line != null); } catch (final IOException e) { Log.e("RetrieveLogTask", "Error loading log", e); formattedText.append("<p><font color=\"#ff0000\">").append(e.toString()).append("</font></p>"); } return formattedText.toString(); }
private void loadUserList() throws IOException { String delimiter = PropertyLoader.getInstance() .load(COMMON_PROPERTIES_PATH).getProperty(DELIMITER); try (InputStream in = Thread.currentThread().getContextClassLoader() .getResourceAsStream("UserList"); BufferedReader reader = new BufferedReader( new InputStreamReader(in));) { userList = new HashMap<String, String>(); String data = null; while ((data = reader.readLine()) != null) { if (!data.trim().isEmpty()) { String[] userData = data.split(delimiter); userList.put(userData[0], userData[1]); } } } }
/** * 메뉴 8-2 저장경로 변경 * @param in * @throws Exception */ private void changeSavePath(final BufferedReader in) throws Exception { System.out.printf("현재 저장경로: %s\n변경할 경로를 입력하세요: ", SystemInfo.PATH); String path = in.readLine().trim(); File newPath = new File(path); /* 입력한 경로가 만든 적이 없는 경로 & 그런데 새로 생성 실패 */ if(newPath.exists()==false && newPath.mkdirs()==false) { ErrorHandling.printError("저장경로 변경 실패", false); return; } /* 생성 가능한 정상적인 경로라면 */ Configuration.setProperty("PATH", path); Configuration.refresh(); //store -> load - > apply System.out.println("저장경로 변경 완료!"); }
private boolean isNeonSupported() { try { BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(new File("/proc/cpuinfo")))); String line = null; while ((line = input.readLine()) != null) { Log.d(TAG, "CPUINFO line: " + line); if(line.toLowerCase().contains("neon")) { return true; } } input.close(); } catch (IOException e) { e.printStackTrace(); } return false; }
private java.util.HashMap loadBlacklist() { java.util.HashMap<String,String> map = new java.util.HashMap<String,String>(); try { java.io.BufferedReader input = new java.io.BufferedReader( new java.io.FileReader( BLACKLISTFILE ) ); java.lang.String line = ""; while ((line = input.readLine()) != null) { if (line.length() <= 7) { map.put( line, line ); } } input.close(); } catch ( java.io.IOException e ) { System.out.println( "File is not found" ); } return map; }
public Main() { try { BufferedReader datafile; datafile = readDataFile("camping.txt"); Instances data = new Instances(datafile); data.setClassIndex(data.numAttributes() - 1); Instances trainingData = new Instances(data, 0, 14); Instances testingData = new Instances(data, 14, 5); Evaluation evaluation = new Evaluation(trainingData); SMO smo = new SMO(); smo.buildClassifier(data); evaluation.evaluateModel(smo, testingData); System.out.println(evaluation.toSummaryString()); // Test instance Instance instance = new DenseInstance(3); instance.setValue(data.attribute("age"), 78); instance.setValue(data.attribute("income"), 125700); instance.setValue(data.attribute("camps"), 1); instance.setDataset(data); System.out.println("The instance: " + instance); System.out.println(smo.classifyInstance(instance)); } catch (Exception ex) { ex.printStackTrace(); } }
private int loadShader(MyFile file, int type) { StringBuilder shaderSource = new StringBuilder(); try { BufferedReader reader = file.getReader(); String line; while ((line = reader.readLine()) != null) { shaderSource.append(line).append("//\n"); } reader.close(); } catch (Exception e) { System.err.println("Could not read file."); e.printStackTrace(); System.exit(-1); } int shaderID = GL20.glCreateShader(type); GL20.glShaderSource(shaderID, shaderSource); GL20.glCompileShader(shaderID); if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) { System.out.println(GL20.glGetShaderInfoLog(shaderID, 500)); System.err.println("Could not compile shader " + file); System.exit(-1); } return shaderID; }
/** * Redid this file to remove sizing requirements and to make it faster * Speeded it up 10 fold. * * @param file */ static String readFile(String file) { try { FileReader reader = new FileReader(file); BufferedReader read = new BufferedReader(reader); StringBuffer b = new StringBuffer(); String s = null; int count = 0; while ((s = read.readLine()) != null) { count++; b.append(s); b.append('\n'); } read.close(); reader.close(); return b.toString(); } catch (IOException e) { return e.toString(); } }
public boolean load(String path) { trie = new BinTrie<Byte>(); if (loadDat(path + Predefine.TRIE_EXT)) return true; String line = null; try { BufferedReader bw = new BufferedReader(new InputStreamReader(IOUtil.newInputStream(path))); while ((line = bw.readLine()) != null) { trie.put(line, null); } bw.close(); } catch (Exception e) { logger.warning("加载" + path + "失败," + e); } if (!trie.save(path + Predefine.TRIE_EXT)) logger.warning("缓存" + path + Predefine.TRIE_EXT + "失败"); return true; }
private void loadAggregatedFile(){ // this function actually loads the aggregated parameter file paramFile = new ArrayList<String>(); try { //System.out.println("Loading Parameters from:\t" + super.parameterFilePath); FileReader reader = new FileReader(new File(super.parameterFilePath)); BufferedReader bufReader = new BufferedReader(reader); String tempLine = ""; while((tempLine = bufReader.readLine()) != null){ paramFile.add(tempLine); } bufReader.close(); } catch (Exception e) { e.printStackTrace(); } this.actions.add("CASH_IN"); this.actions.add("CASH_OUT"); this.actions.add("DEBIT"); this.actions.add("DEPOSIT"); this.actions.add("PAYMENT"); this.actions.add("TRANSFER"); }
@Override public void recover(String path,HttpSession session) throws IOException { initVariableByProperties(); //初始化数据库连接 Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("cmd /c mysql -h "+ hostIP +" -u "+ userName +" -p"+ password +" --default-character-set=utf8 lemon"); OutputStream outputStream = process.getOutputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path))); ProgressSingleton.put(session.getId()+"Size", new File(path).length()); //记录文件大小 //文件进度长度 long progress = 0; String str = null; OutputStreamWriter writer = new OutputStreamWriter(outputStream,"utf-8"); while((str = br.readLine()) != null){ progress = progress + str.length(); //向单例哈希表写入进度 ProgressSingleton.put(session.getId()+"Progress", progress); writer.write(str+"\r\n"); } ProgressSingleton.remove(session.getId()+"Size"); ProgressSingleton.remove(session.getId()+"Progress"); writer.flush(); outputStream.close(); br.close(); writer.close(); }
/** * Extracts the response string from the given HttpEntity. * * @param entity HttpEntity that contains the response * @return response String */ public static String getResponseString(HttpEntity entity) { StringBuilder builder = new StringBuilder(); if (entity != null) { try (BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()))) { String inputLine; while ((inputLine = in.readLine()) != null) { builder.append(inputLine); } } catch (IOException e) { LOGGER.error(e.getMessage(), e); return null; } } return builder.toString(); }
/******************* * Helper method to prompt the user for input (such as commands to execute * as part of an attack). * * @param prompt A prompt asking the user for appropriate input. * @param allowEmpty True if an empty response should be allowed. If false then the prompt will repeat until the user provides input. * @return The user's input. * @throws BaRMIeInputException If an IOException occurs whilst reading input from STDIN. ******************/ protected final String promptUserForInput(String prompt, boolean allowEmpty) throws BaRMIeInputException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = ""; //Enter input loop until we have an acceptable input from the user while(input.equals("") == true) { //Prompt the user System.out.print(prompt); //Attempt to read a line of input try { input = br.readLine(); } catch(IOException ioe) { throw new BaRMIeInputException(ioe); } //Break out of the loop if empty input is allowed if(allowEmpty == true) { break; } } //Return the user input return input; }
@Override public CorpusEventLinking loadCorpusEventFrames(final CharSource source) throws IOException { int lineNo = 1; try (final BufferedReader in = source.openBufferedStream()) { final ImmutableSet.Builder<CorpusEventFrame> ret = ImmutableSet.builder(); String line; while ((line = in.readLine()) != null) { if (!line.isEmpty() && !line.startsWith("#")) { // check for blank or comment lines ret.add(parseLine(line)); } } return CorpusEventLinking.of(ret.build()); } catch (Exception e) { throw new IOException("Error on line " + lineNo + " of " + source, e); } }
/** * * <p> * 读取多线程配置文件 * </p> * * @param fileName * 文件名 * @return 获得的参数 */ public static List<String[]> readRunArgs(String fileName) { URL url = locateFromClasspath(fileName); File file = fileFromURL(url); List<String[]> list = new ArrayList<String[]>(); try { InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8"); BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { if (StringUtils.isNotBlank(lineTxt)) { // #开头为注释行, 略过 if (!lineTxt.startsWith("#")) { list.add(lineTxt.split("\\s")); } } } read.close(); } catch (IOException e) { e.printStackTrace(); } return list; }
/** * Returns a DataFrame parsed from the stream specified stream * @param stream the stream to parse * @return the DataFrame parsed from stream * @throws IOException if there stream read error */ private DataFrame<R,String> parse(CsvSourceOptions<R> options, InputStream stream) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, options.getCharset().orElse(StandardCharsets.UTF_8)))) { final CsvRequestHandler handler = new CsvRequestHandler(options); final CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setDelimiter(options.getDelimiter()); settings.setHeaderExtractionEnabled(options.isHeader()); settings.setLineSeparatorDetectionEnabled(true); settings.setRowProcessor(handler); settings.setIgnoreTrailingWhitespaces(true); settings.setIgnoreLeadingWhitespaces(true); settings.setMaxColumns(10000); settings.setReadInputOnSeparateThread(false); final CsvParser parser = new CsvParser(settings); parser.parse(reader); return handler.getFrame(); } }
static void LoadPerformanceResults(String fileName, HashMap<Short, Pair<Short, Long>> perfResultsSubpartsRaw) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader(fileName)); String strLine; while ((strLine = br.readLine()) != null) { if (strLine.contains("trapID,")) { // skip header line } else { String[] cols = strLine.split(","); Short perfID = Short.parseShort(cols[0].trim()); Short prevPerfID = Short.parseShort(cols[1].trim()); Long elapsed = Long.parseLong(cols[2].trim()); perfResultsSubpartsRaw.put(perfID, new Pair(prevPerfID, elapsed)); } } br.close(); }
/** * Creates a Runnable to for the single thread {@code ExecutorService} to read the command output. * * @param process the process to read from * @param output a list to store the output lines to */ private Runnable outputConsumerRunnable(Process process, List<String> output) { return () -> { try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line = br.readLine(); while (line != null) { if (logger != null) { logger.lifecycle(line); } output.add(line); line = br.readLine(); } } catch (IOException ex) { if (logger != null) { logger.warn("IO Exception reading process output"); } } }; }
private static Difference[] parseNormalDiff(Reader in) throws IOException { Pattern normRegexp; try { normRegexp = Pattern.compile(CmdlineDiffProvider.DIFF_REGEXP); } catch (PatternSyntaxException rsex) { normRegexp = null; } StringBuffer firstText = new StringBuffer(); StringBuffer secondText = new StringBuffer(); BufferedReader br = new BufferedReader(in); List<Difference> diffs = new ArrayList<Difference>(); String line; while ((line = br.readLine()) != null) { CmdlineDiffProvider.outputLine(line, normRegexp, diffs, firstText, secondText); } CmdlineDiffProvider.setTextOnLastDifference(diffs, firstText, secondText); return diffs.toArray(new Difference[diffs.size()]); }
public List<String> linesThat(Matcher<? super String> matcher) { try { BufferedReader reader = new BufferedReader(new FileReader(this)); try { List<String> lines = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { if (matcher.matches(line)) { lines.add(line); } } return lines; } finally { reader.close(); } } catch (IOException e) { throw new RuntimeException(e); } }
public static void createFileByTemplate(Path template, Path out, Map<String, Object> model) throws IOException { if (Files.exists(out) && Files.isRegularFile(out)) { try { Files.delete(out); } catch (Exception ex) { System.out.println("WARNING: " + out.toFile().getAbsolutePath() + " already exists - unable to remove old copy"); ex.printStackTrace(); } } try (BufferedReader br = Files.newBufferedReader(template, Charset.defaultCharset()); BufferedWriter bw = Files.newBufferedWriter(out, Charset.defaultCharset())) { String line; while ((line = br.readLine()) != null) { if (model != null) { for (Map.Entry<String, Object> macro : model.entrySet()) { line = line.replaceAll(Pattern.quote(macro.getKey()), macro.getValue().toString()); } } bw.write(line, 0, line.length()); bw.newLine(); } } }