private static void loadCmdFile(String name, List<String> args) throws IOException { Reader r = new BufferedReader(new FileReader(name)); StreamTokenizer st = new StreamTokenizer(r); st.resetSyntax(); st.wordChars(' ', 255); st.whitespaceChars(0, ' '); st.commentChar('#'); st.quoteChar('"'); st.quoteChar('\''); while (st.nextToken() != StreamTokenizer.TT_EOF) { args.add(st.sval); } r.close(); }
private static void loadCmdFile(String name, List args) throws IOException { Reader r = new BufferedReader(new FileReader(name)); StreamTokenizer st = new StreamTokenizer(r); st.resetSyntax(); st.wordChars(' ', 255); st.whitespaceChars(0, ' '); st.commentChar('#'); st.quoteChar('"'); st.quoteChar('\''); while (st.nextToken() != st.TT_EOF) { args.add(st.sval); } r.close(); }
public static String loadOptions(FileReader fr, String filename) { LineNumberReader lnr = new LineNumberReader(fr); Group.restoreAllDefaults(); String line; try { while ((line = lnr.readLine()) != null) { String reason = Group.root.setOption(line); if (reason != null) { System.err.println("Option "+line+ " at line "+lnr.getLineNumber()+ " ignored: "+reason); } } } catch (IOException e) { Group.restoreAllDefaults(); return ("IO Error reading "+filename+ " at line "+lnr.getLineNumber()); } return null; }
public String readJSON() { try { Object obj = parser.parse(new FileReader(jsonFile)); JSONObject jsonObject = (JSONObject) obj; jsonString = JSONWriter.getJSONString(jsonObject); } catch (IOException | ParseException ex) { Logger.getLogger(ParseJSON.class.getName()).log(Level.SEVERE, null, ex); } return jsonString; }
public static List<ResultList> getResultsTXT(File f, Map<String, MassBank> dbFiles) throws Exception{ List<ResultList> results=new ArrayList<ResultList>(); BufferedReader br=new BufferedReader(new FileReader(f)); String line; ResultList rl=null; while((line=br.readLine())!=null){ if(line.startsWith("query")){ rl=new ResultList(); results.add(rl); Query q=new Query(line.split("\t")[1]); q.massbank=dbFiles.get(q.queryID); rl.query=q; }else if(line.startsWith("result")){ Result r=new Result(line.split("\t")); r.massbank=dbFiles.get(r.resultID); rl.results.add(r); r.isTrueMatch=rl.query.massbank.inchi.equals(r.massbank.inchi); } } br.close(); return results; }
private void init(PaySim paysim){ this.paysim = paysim; try { File f = new File(this.paysim.getTransferMaxPath()); FileReader reader = new FileReader(f); BufferedReader bufReader = new BufferedReader(reader); String line = ""; while((line = bufReader.readLine()) != null){ this.fileContents.add(line); } bufReader.close(); } catch (Exception e) { e.printStackTrace(); } initMax(this.fileContents); this.multiplier = this.paysim.getMultiplier(); }
/** * Utility method used to obtain the name of an user based on an uid */ private final String getPUID(final String uid) { if (pids.containsKey(uid)) return pids.get(uid); final String pat = "([\\S&&[^:]]+):[\\S&&[^:]]+:" + uid + ":"; final Pattern pattern = PatternUtil.getPattern("uid_" + uid, pat); try { BufferedReader in = new BufferedReader(new FileReader("/etc/passwd")); String line; while ((line = in.readLine()) != null) { final Matcher matcher = pattern.matcher(line); if (matcher.find()) { final String puid = matcher.group(1); pids.put(uid, puid); return puid; } } in.close(); } catch (Throwable t) { } pids.put(uid, "UNKNOWN"); return "UNKNOWN"; }
private static String readFileToString(String filePath) { StringBuilder fileData = new StringBuilder(1000); try { BufferedReader reader = new BufferedReader(new FileReader(filePath)); char[] buf = new char[10]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } reader.close(); } catch(IOException e) { e.printStackTrace(); } return fileData.toString(); }
public static void convertFiles(OutputStream output, File[] files) throws IOException { Context context = new Context(); context.appender = new OutputStreamAppender(output); for (File file : files) { context.currentMember = null; BufferedReader reader = new BufferedReader(new FileReader(file)); try { String line; while ((line = reader.readLine()) != null) { for (Test test : tests) { if (test.apply(context, line)) { // go to the next line break; } } } } finally { reader.close(); } } }
@Override public void onEnable() { try { uuid_map = new HashMap<String, UUID>(); getConfig().options().copyDefaults(true); saveConfig(); initializeLocal(); registerEvents(); registerCommands(); if(uuidFile.exists()) { BufferedReader reader = new BufferedReader(new FileReader(uuidFile)); byte[] bytes = reader.readLine().getBytes(Charsets.UTF_8); uuid_map = Serializer.<Map<String, UUID>>deserializeBase64(bytes); reader.close(); } else { uuidFile.createNewFile(); } } catch (Exception | Error e) { getLogger().log(Level.WARNING, e.getMessage(), e); } }
/** * Creates a new instance of a data set, stored in a file. When this object * is initialized, the file is read into memory. * * @param datafile The file containing the data set * @throws java.io.IOException when a I/O error is found * @throws java.lang.ArrayIndexOutOfBoundsException when the file has not * consistent number of columns * @throws java.lang.NumberFormatException when the numbers inside the file * are not parsable */ public FileDataSet(File datafile) throws IOException, NumberFormatException, ArrayIndexOutOfBoundsException { super(true); BufferedReader in = new BufferedReader(new FileReader(datafile)); String line; List<String> data; while ((line = in.readLine()) != null && (!line.equals(""))) { line = line.trim(); if (!line.startsWith("#")) { data = new ArrayList<String>(); StringTokenizer tk = new StringTokenizer(line); while (tk.hasMoreTokens()) data.add(tk.nextToken()); add(data); } } }
public void demoToCreateWriteAndReadFromFile() throws IOException { File file = new File("project.txt"); file.createNewFile(); FileWriter fileWriter = new FileWriter(file); fileWriter.write ("Hugo Boss \n Gucci \n Tommy Hilfiger \n Armani \n Salvatore \n Dolce & Gabbana \n"); fileWriter.flush(); fileWriter.close(); FileReader fileReader = new FileReader(file); char[] charArrays = new char[100]; fileReader.read(charArrays); for (char charArray : charArrays) { System.out.println(charArray); fileReader.close(); } }
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 ArrayList<String> listOfProbs(){ ArrayList<String> allContents = new ArrayList<String>(); File f = new File(transferFreqMod); try { BufferedReader reader = new BufferedReader(new FileReader(f)); String line = ""; while((line = reader.readLine()) != null){ allContents.add(line); } reader.close(); } catch (Exception e) { e.printStackTrace(); } return allContents; }
public static byte[] lerArquivo(File arquivo) throws Exception { byte[] bytes; try (FileReader arq = new FileReader(arquivo)) { BufferedReader lerArq = new BufferedReader(arq); String linha = lerArq.readLine(); String conteudo = linha; while (linha != null) { linha = lerArq.readLine(); // lê da segunda até a última linha if (linha != null){ conteudo += linha; } } bytes = conteudo.getBytes(); } return bytes; }
public LSDAlchemyRuleReader(File inputFile) { ArrayList<LSDRule> rs = new ArrayList<LSDRule>(); try { if (inputFile.exists()) { BufferedReader in = new BufferedReader( new FileReader(inputFile)); String line = null; while ((line=in.readLine())!= null){ if (line.trim().equals("") || line.trim().charAt(0) == '#') continue; LSDRule rule = parseAlchemyRule(line); rs.add(rule); } in.close(); } this.rules= rs; } catch (IOException e) { e.printStackTrace(); } }
/** * Set the list of predicates for which the ExtVP tables will be calculated, * if list of predicates is given, that list is used. * * @param TripleTable - Table containing all triples. * * @throws IllegalArgumentException * @throws SQLException */ private void setListOfPredicates(String TripleTable) throws IllegalArgumentException, SQLException { if (path_of_list_of_predicates != "\\n") { System.out.println(String.format("Path for list of predicates is given: %s", path_of_list_of_predicates)); try { BufferedReader br = new BufferedReader(new FileReader(path_of_list_of_predicates)); for (String line; (line = br.readLine()) != null;) { ListOfPredicates.add(line); } br.close(); } catch (IOException e) { System.err.println("[ERROR] Could not open list of predicates file. Reason: " + e.getMessage()); System.exit(1); } } else { System.out.println("Get All predicates"); ResultSet DataSet = impala.select(column_name_predicate).distinct().from(TripleTable).execute(); while (DataSet.next()) { ListOfPredicates.add(DataSet.getString(column_name_predicate)); } } java.util.Collections.sort(ListOfPredicates); }
/** * 读取文件的内容 * 读取指定文件的内容 * @param path 为要读取文件的绝对路径 * @return 以行读取文件后的内容。 * @since 1.0 */ public static final String getFileContent(String path) throws IOException { String filecontent = ""; try { File f = new File(path); if (f.exists()) { FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); //建立BufferedReader对象,并实例化为br String line = br.readLine(); //从文件读取一行字符串 //判断读取到的字符串是否不为空 while (line != null) { filecontent += line + "\n"; line = br.readLine(); //从文件中继续读取一行数据 } br.close(); //关闭BufferedReader对象 fr.close(); //关闭文件 } } catch (IOException e) { throw e; } return filecontent; }
private static void readCustomAndAddedTypesInGivenDirectory(String directoryPath, Map nodes, Map capabilities, Map relationships, Map policies) throws Exception { File[] yamlFiles = new File(directoryPath).listFiles(); for (File path : yamlFiles) { YamlReader reader = new YamlReader(new FileReader(path)); Map<String, ?> map = (Map<String, ?>) reader.read(); if (map.containsKey("node_types")) { nodes.putAll((Map) map.get("node_types")); } if (map.containsKey("capability_types")) { capabilities.putAll((Map) map.get("capability_types")); } if (map.containsKey("relationship_types")) { relationships.putAll((Map) map.get("relationship_types")); } if (map.containsKey("policy_types")) { policies.putAll((Map) map.get("policy_types")); } reader.close(); } }
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; }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test public void testLoad_LoadExistingSuccess() throws Exception { Class configClass = JsonConfig.class; JsonConfig jsonConfig = new JsonConfig(); PowerMockito.mockStatic(JsonUtils.class); File mockFile = PowerMockito.mock(File.class); FileReader mockFileReader = PowerMockito.mock(FileReader.class); Mockito.when(mockFile.exists()).thenReturn(true); Mockito.when(mockFile.length()).thenReturn(1l); PowerMockito.whenNew(FileReader.class).withParameterTypes(File.class).withArguments(mockFile).thenReturn(mockFileReader); PowerMockito.when(JsonUtils.convertJsonFromFileReaderToObject(Mockito.isA(Gson.class), Mockito.isA(FileReader.class), Mockito.isA(Class.class))).thenReturn(jsonConfig); JsonConfig response = JsonConfig.load(mockFile, configClass); assertThat(response).isNotNull(); Mockito.verify(mockFile, Mockito.times(1)).exists(); Mockito.verify(mockFile, Mockito.times(1)).length(); PowerMockito.verifyNew(FileReader.class, Mockito.times(1)).withArguments(Mockito.isA(File.class)); }
public static String read(File f) { String text=""; int read,N=1024*1024; char[] buffer=new char[N]; try { FileReader fr=new FileReader(f); BufferedReader br =new BufferedReader(fr); while(true) { read=br.read(buffer,0,N); text+=new String(buffer,0,read); if(read<N) break; } br.close(); return text; } catch(Exception ex) { ex.printStackTrace(); } return null; }
/** * This method returns a list of bookmarks located in the specified folder * * @param folder * @return */ private synchronized List<HistoryItem> getBookmarksFromFolder(String folder) { List<HistoryItem> bookmarks = new ArrayList<>(); File bookmarksFile = new File(mContext.getFilesDir(), FILE_BOOKMARKS); try { BufferedReader bookmarksReader = new BufferedReader(new FileReader(bookmarksFile)); String line; while ((line = bookmarksReader.readLine()) != null) { JSONObject object = new JSONObject(line); if (object.getString(FOLDER).equals(folder)) { HistoryItem item = new HistoryItem(); item.setTitle(object.getString(TITLE)); item.setUrl(object.getString(URL)); item.setFolder(object.getString(FOLDER)); item.setOrder(object.getInt(ORDER)); item.setImageId(R.drawable.ic_bookmark); bookmarks.add(item); } } bookmarksReader.close(); } catch (IOException | JSONException e) { e.printStackTrace(); } return bookmarks; }
public static void main(String[] args) throws IOException { Scanner sc1 = new Scanner(System.in); Scanner sc2 = new Scanner("10 20 30"); Scanner sc3 = new Scanner(new FileReader("a.txt")); Scanner sc = sc1; int num1 = sc.nextInt(); int num2 = sc.nextInt(); int num3 = sc.nextInt(); int sum = num1 + num2 + num3; System.out.printf("%d + %d + %d = %d", num1, num2, num3, sum); sc.close(); }
private void loadServers() { File[] files = mServersPath.listFiles(); if (files == null) return; for (File f : files) { if (!f.isFile() || !f.getName().startsWith(SERVER_FILE_PREFIX) || !f.getName().endsWith(SERVER_FILE_SUFFIX)) continue; try { ServerConfigData data = SettingsHelper.getGson().fromJson(new BufferedReader(new FileReader(f)), ServerConfigData.class); mServers.add(data); mServersMap.put(data.uuid, data); } catch (IOException e) { Log.e(TAG, "Failed to load server data"); e.printStackTrace(); } } }
public static Properties loadPropertiesfile(String filePath) { Properties properties = new Properties(); try { // properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath)); FileReader fr = new FileReader(new File(filePath)); properties.load(fr); } catch (IOException e) { log(10, "The properties file is not loaded.\r\n" + e); throw new IllegalArgumentException("The properties file is not loaded.\r\n" + e); } return properties; }
public static void main(String[] args) throws IOException { File dir = new File(MESSAGES_DIR); List<File> files = new LinkedList<File>(); for (File f : dir.listFiles()) { if (!f.isFile()) continue; files.add(f); } int i = 0; for (File file : files) { ++i; System.out.println(i + "/" + files.size() + " " + file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("\\")+1, file.getAbsolutePath().length())); FileReader reader = new FileReader(file); File output = new File(WORKING_DIR + "\\temp.xml"); FileWriter writer = new FileWriter(output); Rewriter rewriter = new Rewriter(reader, writer); rewriter.rewrite(); file.delete(); output.renameTo(new File(MESSAGES_DIR + "\\" + file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("\\")+1, file.getAbsolutePath().length()))); } System.out.println("DONE"); }
public Config() throws Exception { configFile = new File("config.json"); if(!configFile.exists()) { URL configResource = getClass().getClassLoader().getResource("config.json"); FileUtils.copyURLToFile(configResource, configFile); } FileReader reader = new FileReader(configFile); json = new JSONObject(IOUtils.toString(reader)); reader.close(); }
public static Map<String, String> loadTexts(final EDataset dataset) throws IOException { HashMap<String, String> texts = new HashMap<String, String>(); final String inputFileName; inputFileName = getInputFileName(dataset); BufferedReader br = new BufferedReader(new FileReader(new File(inputFileName))); String line = ""; StringBuffer abstarctText = new StringBuffer(); String pubmedID = null; while ((line = br.readLine()) != null) { if (line.trim().isEmpty() || line.startsWith("#")) continue; /* * Filter abstract lines and store them. */ if (line.matches("[0-9]+\\|[ta]\\|.*")) { abstarctText.append(line.split("\\|")[2]); abstarctText.append(" "); pubmedID = line.split("\\|")[0]; continue; } if (abstarctText.length() > 0) { texts.put(pubmedID, abstarctText.toString()); abstarctText = new StringBuffer(); } } br.close(); return texts; }
public InputLoader(Parameter param, String fileName, VariableMapping[] map, ProgressShow prg) throws FileNotFoundException { super(prg); this.param = param; this.map = map; valori = new ArrayList<Observation>(); reader = new BufferedReader(new FileReader(fileName)); }
public BookDecisionTree(String fileName) { try { BufferedReader reader = new BufferedReader(new FileReader(fileName)); trainingData = new Instances(reader); trainingData.setClassIndex(trainingData.numAttributes() - 1); } catch (IOException ex) { ex.printStackTrace(); } }
boolean expansionFilesUptoData() { File cacheFile = getFileDetailsCacheFile(); // Read data into an array or something... Map<String, Long> fileDetailsMap = new HashMap<String, Long>(); if(cacheFile.exists()) { try { FileReader fileCache = new FileReader(cacheFile); BufferedReader bufferedFileCache = new BufferedReader(fileCache); List<String> lines = new ArrayList<String>(); String line = null; while ((line = bufferedFileCache.readLine()) != null) { lines.add(line); } bufferedFileCache.close(); for(String dataLine : lines) { GameActivity.Log.debug("Splitting dataLine => " + dataLine); String[] parts = dataLine.split(","); fileDetailsMap.put(parts[0], Long.parseLong(parts[1])); } } catch(Exception e) { GameActivity.Log.debug("Exception thrown during file details reading."); e.printStackTrace(); fileDetailsMap.clear(); } } for (OBBData.XAPKFile xf : OBBData.xAPKS) { String fileName = Helpers.getExpansionAPKFileName(this, xf.mIsMain, xf.mFileVersion); String fileForNewFile = Helpers.generateSaveFileName(this, fileName); String fileForDevFile = Helpers.generateSaveFileNameDevelopment(this, fileName); // check to see if time/data on files match cached version // if not return false File srcFile = new File(fileForNewFile); File srcDevFile = new File(fileForDevFile); long lastModified = srcFile.lastModified(); long lastModifiedDev = srcDevFile.lastModified(); if(!(srcFile.exists() && fileDetailsMap.containsKey(fileName) && lastModified == fileDetailsMap.get(fileName)) && !(srcDevFile.exists() && fileDetailsMap.containsKey(fileName) && lastModifiedDev == fileDetailsMap.get(fileName))) return false; } return true; }
public String callService(String service, String method, ArrayList<functionParam> params){ JSONObject reply = null; try { JSONParser parser = new JSONParser(); JSONObject reqJson = (JSONObject)parser.parse(new FileReader(tmpDir+"request.json")); String currSvc = (String)reqJson.get("svcName"); String currFunc = (String)reqJson.get("funcName"); String serviceReplyMq = (String)reqJson.get("serviceReplyMq"); reqJson.put("svcName", service); reqJson.put("funcName", method); if(reqJson.containsKey("serverId")) reqJson.remove("serverId"); if(reqJson.containsKey("processId")) reqJson.remove("processId"); JSONArray paramArr = new JSONArray(); for(int i=0; i<params.size(); i++){ functionParam p = params.get(i); JSONObject param = new JSONObject(); String paramNum = "param" + ((Integer)(i+1)).toString(); param.put("name", paramNum); param.put("type", p.type); param.put("value", p.value.toString()); paramArr.add(param); } reqJson.put("params", paramArr); String stack = (String)reqJson.get("stack"); stack = stack + "|" + currSvc + ":" + currFunc; reqJson.put("stack", stack); //System.out.println(reqJson.toJSONString()); this.connectToBroker(); this.send("svcQueue"+service, reqJson, serviceReplyMq); reply = this.listenAndFilter(); } catch(Exception e){ doLogging(e.getMessage(), "Error-CSVCFW"); } return reply.get("response").toString(); }
/** * Read the Json data and load the network * * @param jsonFile */ public void load(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String line = null; StringBuilder stringBuilder = new StringBuilder(); String ls = System.getProperty("line.separator"); while ((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append(ls); } reader.close(); load(stringBuilder.toString()); }
public static Map<Integer,String> getInchiKeysByID(File inchiKeysFile) throws Exception{ Map<Integer,String> inchis=new HashMap<Integer,String>(); BufferedReader br=new BufferedReader(new FileReader(inchiKeysFile)); String line=br.readLine(); List<String> header=Arrays.asList(line.split("\t",Integer.MAX_VALUE)); while((line=br.readLine())!=null){ String l[]=line.replaceAll("\"","").split("\t",Integer.MAX_VALUE); if(l.length!=header.size())l=line.split(","); int id=Integer.parseInt(l[header.indexOf("id")]); String inchiTmp=l[header.indexOf("inchi")].replaceAll("\"",""); if(!inchiTmp.isEmpty()){ String[] isplit=inchiTmp.split("/"); if(isplit.length>=3&&!isplit[2].startsWith("c")){ System.out.print(inchiTmp); System.out.println(); } if(isplit.length>=4&&!isplit[3].startsWith("h")){ System.out.print(inchiTmp); System.out.println(); } String inchi=isplit[0]+"/"+isplit[1]+(isplit.length>=3&&(isplit[2].startsWith("c")||isplit[2].startsWith("h"))?("/"+isplit[2]):"")+(isplit.length>=4&&isplit[3].startsWith("h")?("/"+isplit[3]):""); inchis.put(id, inchi); } } br.close(); return inchis; }
/** * 读取文件内容 */ private void readFile() { StringBuilder sb = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(new File(FILE_DIR, FILE_NAME)));//构造一个BufferedReader类来读取文件 String s; while ((s = br.readLine()) != null) { sb.append(s); } br.close(); } catch (Exception e) { e.printStackTrace(); } ArrayList<SlideSetInfo> list = new Gson().fromJson(sb.toString(), new TypeToken<List<SlideSetInfo>>() { }.getType()); mData.clear(); if (list != null && list.size() > 0) { for (SlideSetInfo bean : list) { if ( bean.imageList == null || bean.imageList.size()==0) { return; } for (int i = bean.imageList.size() - 1; i >= 0; i--) { boolean exists = fileIsExists(bean.imageList.get(i)); if (!exists) { bean.imageList.remove(i); } } mData.add(bean); } } }