java.io.FileReader Java Examples

The following examples show how to use java.io.FileReader. 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: PerfTests.java    From JCMathLib with MIT License 6 votes vote down vote up
static void LoadPerformanceResults(String fileName, HashMap<Short, Entry<Short, Long>> perfResultsSubpartsRaw) throws FileNotFoundException, IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    String strLine;
    while ((strLine = br.readLine()) != null) {
        if (strLine.contains("perfID,")) {
            // 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 SimpleEntry(prevPerfID, elapsed));
        }
    }
    br.close();
}
 
Example #2
Source File: VideoEditor.java    From WeiXinRecordedDemo with MIT License 6 votes vote down vote up
private static int checkCPUName() {
        String str1 = "/proc/cpuinfo";
        String str2 = "";
        try {
            FileReader fr = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
            str2 = localBufferedReader.readLine();
            while (str2 != null) {
//                Log.i("testCPU","->"+str2+"<-");
                str2 = localBufferedReader.readLine();
                if(str2.contains("SDM845")){  //845的平台;

                }
            }
            localBufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
 
Example #3
Source File: Relation.java    From metanome-algorithms with Apache License 2.0 6 votes vote down vote up
public Relation(String path, String seperator){
	stringTuples = new ArrayList<StringTuple>();
	positionListIndices = new ArrayList<PositionListIndex>();
	try(BufferedReader br = new BufferedReader(new FileReader(path))) {
	    String line = br.readLine();
	    if (line != null)
	    	attributeCount = line.split(seperator).length;

	    while (line != null) {
	    	addTuple(new StringTuple(line, seperator));
	        line = br.readLine();
	    }
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example #4
Source File: Solution.java    From JavaRushTasks with MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    TreeSet<Character> letters = new TreeSet<>();
    try (BufferedReader fileReader = new BufferedReader(new FileReader(args[0]))) {
        while (fileReader.ready()) {
            String s = fileReader.readLine().toLowerCase().replaceAll("[^\\p{Alpha}]",""); //\s\p{Punct}
            for (int i = 0; i < s.length(); i++)
                letters.add(s.charAt(i));
        }
    }

    Iterator<Character> iterator = letters.iterator();
    int n = letters.size() < 5 ? letters.size() : 5;

    for (int i = 0; i < n; i++) {
        System.out.print((iterator.next()));
    }
}
 
Example #5
Source File: DFActorManagerJs.java    From dfactor with MIT License 6 votes vote down vote up
private boolean _initSysScript(File dir){
	boolean bRet = false;
	do {
		try {
			File f = new File(dir.getAbsolutePath()+File.separator+"Init.js");
			if(!f.exists()){
				printError("invalid sys script: "+f.getAbsolutePath());
				break;
			}
			//
			if(!_checkScriptFileValid(f)){
				printError("add "+f.getAbsolutePath()+" failed");
				break;
			}
			_jsEngine.eval(new FileReader(f));
		} catch (FileNotFoundException | ScriptException e) {
			e.printStackTrace();
		}
		bRet = true;
	} while (false);
	return bRet;
}
 
Example #6
Source File: PerformanceReportN4jscJarTest.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void makeAssertions(CliCompileResult cliResult) throws IOException {
	assertEquals(cliResult.toString(), 1, cliResult.getTranspiledFilesCount());

	// find the actual report file (i.e. the one with the time stamp added to its name)
	File folder = PERFORMANCE_REPORT_FILE.getParentFile();
	File[] matches = folder.listFiles((dir, name) -> name.startsWith(PERFORMANCE_REPORT_FILE_NAME_WITHOUT_EXTENSION)
			&& name.endsWith(PERFORMANCE_REPORT_FILE_EXTENSION));
	assertTrue("Report file is missing", matches.length > 0);
	assertEquals("expected exactly 1 matching file but got: " + matches.length, 1, matches.length);
	File actualReportFile = matches[0];

	// check performance report
	try (FileReader reader = new FileReader(actualReportFile)) {
		final List<String> rows = CharStreams.readLines(reader);
		assertEquals("Performance report contains 2 rows", 2, rows.size());
		String substring = rows.get(1).substring(0, 1);
		assertNotEquals("Performance report has measurement different from 0 in first column of second row", "0",
				substring);
	}
}
 
Example #7
Source File: Test8.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println("\nTest8\n");
    ScriptEngineManager m = new ScriptEngineManager();
    ScriptEngine e  = Helper.getJsEngine(m);
    if (e == null) {
        System.out.println("Warning: No js engine found; test vacuously passes.");
        return;
    }
    e.eval(new FileReader(
        new File(System.getProperty("test.src", "."), "Test8.js")));
    Invocable inv = (Invocable)e;
    inv.invokeFunction("main", "Mustang");
    // use method of a specific script object
    Object scriptObj = e.get("scriptObj");
    inv.invokeMethod(scriptObj, "main", "Mustang");
}
 
Example #8
Source File: XMLProcessingDemo.java    From Natural-Language-Processing-with-Java-Second-Edition with MIT License 6 votes vote down vote up
public static void main(String args[]){
    try {
        Reader reader = new FileReader(getResourcePath());
        DocumentPreprocessor dp = new DocumentPreprocessor(reader, DocumentPreprocessor.DocType.XML);
        dp.setElementDelimiter("sentence");
        for(List sentence : dp){
            ListIterator list = sentence.listIterator();
            while (list.hasNext()) { 
                System.out.print(list.next() + " "); 
            } 
            System.out.println(); 
            
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(XMLProcessingDemo.class.getName()).log(Level.SEVERE, null, ex);
    }
    
}
 
Example #9
Source File: SaasClientPhpAuthenticationGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void replaceTokens(FileObject fO, Map<String, String> tokens) throws IOException {
    FileLock lock = fO.lock();
    try {
        BufferedReader reader = new BufferedReader(new FileReader(FileUtil.toFile(fO)));
        String line;
        StringBuffer sb = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            for(Map.Entry e:tokens.entrySet()) {
                String key = (String) e.getKey();
                String value = (String) e.getValue();
                line = line.replaceAll(key, value);
            }
            sb.append(line+"\n");
        }
        OutputStreamWriter writer = new OutputStreamWriter(fO.getOutputStream(lock), "UTF-8");
        try {
            writer.write(sb.toString());
        } finally {
            writer.close();
        }
    } finally {
        lock.releaseLock();
    }
}
 
Example #10
Source File: InitializrSpringCloudInfoServiceTests.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
@Test
public void getSpringCloudReleaseVersionTest() throws Exception {
	String bomVersion = "vHoxton.BUILD-SNAPSHOT";
	RestTemplate rest = mock(RestTemplate.class);
	Github github = mock(Github.class);
	GithubPomReader githubPomReader = mock(GithubPomReader.class);
	when(githubPomReader.readPomFromUrl(eq(String
			.format(SpringCloudRelease.SPRING_CLOUD_STARTER_PARENT_RAW, bomVersion))))
					.thenReturn(new MavenXpp3Reader()
							.read(new FileReader(new ClassPathResource(
									"spring-cloud-starter-parent-pom.xml")
											.getFile())));
	when(githubPomReader.readPomFromUrl(eq(String.format(
			SpringCloudRelease.SPRING_CLOUD_RELEASE_DEPENDENCIES_RAW, bomVersion))))
					.thenReturn(new MavenXpp3Reader().read(new FileReader(
							new ClassPathResource("spring-cloud-dependencies-pom.xml")
									.getFile())));
	InitializrSpringCloudInfoService service = spy(
			new InitializrSpringCloudInfoService(rest, github, githubPomReader));
	doReturn(Arrays.asList(new String[] { bomVersion })).when(service)
			.getSpringCloudVersions();
	Map<String, String> releaseVersionsResult = service
			.getReleaseVersions(bomVersion);
	assertThat(releaseVersionsResult,
			Matchers.equalTo(SpringCloudInfoTestData.releaseVersions));
}
 
Example #11
Source File: AqlCmdLine.java    From CQL with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String openCan(String can) {
	try {
		String s = Util.readFile(new FileReader(new File(can)));
		Program<Exp<?>> program = AqlParserFactory.getParser().parseProgram(s);
		AqlEnv env = new AqlEnv(program);
		env.typing = new AqlTyping(program, false);
		String html = "";
		for (String n : program.order) {
			Exp<?> exp = program.exps.get(n);
			Object val = Util.timeout(() -> exp.eval(env, false),
					(Long) exp.getOrDefault(env, AqlOption.timeout) * 1000);
			if (val == null) {
				throw new RuntimeException("anomaly, please report: null result on " + exp);
			} else if (exp.kind().equals(Kind.PRAGMA)) {
				((Pragma) val).execute();
			}
			env.defs.put(n, exp.kind(), val);
			html += exp.kind() + " " + n + " = " + val + "\n\n";
		}
		return html.trim();
	} catch (Throwable ex) {
		ex.printStackTrace();
		return "ERROR " + ex.getMessage();
	}
}
 
Example #12
Source File: CommandLine.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #13
Source File: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static String readFileContentToString(File file) throws IOException {
    StringBuffer buff = new StringBuffer();

    BufferedReader rdr = new BufferedReader(new FileReader(file));

    String line;

    try{
        while ((line = rdr.readLine()) != null){
            buff.append(line).append("\n");
        }
    } finally{
        rdr.close();
    }
    
    return buff.toString();
}
 
Example #14
Source File: TestMicroIntegratorRegistry.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegistryResourceDeployment() throws IOException {

    File resourceFile = Paths.get(governanceRegistry.toString(), "custom", "checkJsScript.js").toFile();
    Assert.assertTrue("checkJsScript.js file should be created", resourceFile.exists());

    File metadataFile =
            Paths.get(governanceRegistry.toString(), "custom", ".metadata", "checkJsScript.js.meta").toFile();
    Assert.assertTrue(".metadata/checkJsScript.js.meta file should be created", metadataFile.exists());

    Properties metadata = new Properties();
    try (BufferedReader reader = new BufferedReader(new FileReader(metadataFile))) {
        metadata.load(reader);
    }
    String mediaType = metadata.getProperty("mediaType");
    Assert.assertEquals("Media type should be as expected", "application/javascript", mediaType);
}
 
Example #15
Source File: J2DBench.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #16
Source File: FileUtils.java    From kitty with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 读取txt文件的内容
 * @param file 想要读取的文件对象
 * @return 返回文件内容
 */
public static String readFile(File file){
    StringBuilder result = new StringBuilder();
    try{
        BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
        String s = null;
        while((s = br.readLine())!=null){
        	//使用readLine方法,一次读一行
            result.append(System.lineSeparator() + s);
        }
        br.close();    
    }catch(Exception e){
        e.printStackTrace();
    }
    return result.toString();
}
 
Example #17
Source File: ShopApp.java    From OrionAlpha with GNU General Public License v3.0 6 votes vote down vote up
private void connectCenter() {
    try (JsonReader reader = Json.createReader(new FileReader("Shop.img"))) {
        JsonObject shopData = reader.readObject();
        
        Integer world = shopData.getInt("gameWorldId", getWorldID());
        if (world != getWorldID()) {
            //this.worldID = world.byteValue();
        }

        this.addr = shopData.getString("PublicIP", "127.0.0.1");
        this.port = (short) shopData.getInt("port", 8787);
        
        JsonObject loginData = shopData.getJsonObject("login");
        if (loginData != null) {
            this.socket = new CenterSocket();
            this.socket.init(loginData);
            this.socket.connect();
        }
        
    } catch (FileNotFoundException ex) {
        ex.printStackTrace(System.err);
    }
}
 
Example #18
Source File: Windows.java    From FirefoxReality with Mozilla Public License 2.0 6 votes vote down vote up
private WindowsState restoreState() {
    WindowsState restored = null;

    File file = new File(mContext.getFilesDir(), WINDOWS_SAVE_FILENAME);
    try (Reader reader = new FileReader(file)) {
        Gson gson = new GsonBuilder().create();
        Type type = new TypeToken<WindowsState>() {}.getType();
        restored = gson.fromJson(reader, type);

        Log.d(LOGTAG, "Windows state restored");

    } catch (Exception e) {
        Log.w(LOGTAG, "Error restoring windows state: " + e.getLocalizedMessage());

    } finally {
        file.delete();
    }

    return restored;
}
 
Example #19
Source File: SnippetLoader.java    From genesis with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Loads a file from the disk and creates a JSON object from it.
 *
 * @param file The file to be read
 * @return the content of the file in the form of a JSON object
 * @throws FileNotFoundException is thrown if the file cannot be found
 * @throws IOException is thrown if something goes wrong when accessing the
 * file
 */
private JSONObject loadFileFromDisk(File file) throws FileNotFoundException, IOException {
    //Try to open the file using a file reader in a buffered reader to minimise the amount of system calls (and thus load on the system)
    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        //Creates a new string builder object
        StringBuilder sb = new StringBuilder();
        //Reads a line from the buffered reader
        String line = br.readLine();

        //As long as the line is not null, it means that there is line
        while (line != null) {
            //The current line is appended
            sb.append(line);
            //A line separator is added based on the operating system
            sb.append(System.lineSeparator());
            //The next line is read
            line = br.readLine();
        }
        //Return the string in the form of a JSON object
        return new JSONObject(sb.toString());
    }
}
 
Example #20
Source File: FileTreeServiceImpl.java    From opscenter with Apache License 2.0 6 votes vote down vote up
/**
 * 读取文件
 * @param file
 * @return
 * @throws Exception 
 */
public String read(String file) throws IOException {
	StringBuilder result = new StringBuilder();
	try {
		// 构造一个BufferedReader类来读取文件
		BufferedReader br = new BufferedReader(new FileReader(file));
		String s = null;
		// 使用readLine方法,一次读一行
		while ((s = br.readLine()) != null) {
			result.append(System.lineSeparator() + s);
		}
		br.close();
	} catch (IOException e) {
		throw e;
	}
	return result.toString();
}
 
Example #21
Source File: Hardware.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the size of the physical memory in bytes on a Linux-based
 * operating system.
 * 
 * @return the size of the physical memory in bytes or {@code -1}, if
 *         the size could not be determined
 */
private static long getSizeOfPhysicalMemoryForLinux() {
	try (BufferedReader lineReader = new BufferedReader(new FileReader(LINUX_MEMORY_INFO_PATH))) {
		String line;
		while ((line = lineReader.readLine()) != null) {
			Matcher matcher = LINUX_MEMORY_REGEX.matcher(line);
			if (matcher.matches()) {
				String totalMemory = matcher.group(1);
				return Long.parseLong(totalMemory) * 1024L; // Convert from kilobyte to byte
			}
		}
		// expected line did not come
		LOG.error("Cannot determine the size of the physical memory for Linux host (using '/proc/meminfo'). " +
				"Unexpected format.");
		return -1;
	}
	catch (NumberFormatException e) {
		LOG.error("Cannot determine the size of the physical memory for Linux host (using '/proc/meminfo'). " +
				"Unexpected format.");
		return -1;
	}
	catch (Throwable t) {
		LOG.error("Cannot determine the size of the physical memory for Linux host (using '/proc/meminfo') ", t);
		return -1;
	}
}
 
Example #22
Source File: CatalanoFilterTest.java    From AILibs with GNU Affero General Public License v3.0 6 votes vote down vote up
public void testCatalanoWrapper() throws Exception {
	OpenmlConnector connector = new OpenmlConnector();
	DataSetDescription ds = connector.dataGet(DataSetUtils.MNIST_ID);
	File file = ds.getDataset("4350e421cdc16404033ef1812ea38c01");
	Instances data = new Instances(new BufferedReader(new FileReader(file)));
	data.setClassIndex(data.numAttributes() - 1);
	List<Instances> split = WekaUtil.getStratifiedSplit(data, 42, .25f);

	logger.info("Calculating intermediates...");
	List<INDArray> intermediate = new ArrayList<>();
	for (Instance inst : split.get(0)) {
		intermediate.add(DataSetUtils.instanceToMatrixByDataSet(inst, DataSetUtils.MNIST_ID));
	}
	logger.info("Finished intermediate calculations.");
	DataSet originDataSet = new DataSet(split.get(0), intermediate);

	CatalanoInPlaceFilter filter = new CatalanoInPlaceFilter("GaborFilter");
	// IdentityFilter filter = new IdentityFilter();
	DataSet transDataSet = filter.applyFilter(originDataSet, true);
	transDataSet.updateInstances();

	System.out.println(Arrays.toString(transDataSet.getInstances().get(0).toDoubleArray()));
}
 
Example #23
Source File: SSH2Holders.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * Get local current user ssh authentication private key of default.
 * 
 * @param host
 * @param user
 * @return
 * @throws Exception
 */
protected final char[] getDefaultLocalUserPrivateKey() throws Exception {
	// Check private key.
	File privateKeyFile = new File(USER_HOME + "/.ssh/id_rsa");
	isTrue(privateKeyFile.exists(), String.format("Not found privateKey for %s", privateKeyFile));

	log.warn("Fallback use local user pemPrivateKey of: {}", privateKeyFile);
	try (CharArrayWriter cw = new CharArrayWriter(); FileReader fr = new FileReader(privateKeyFile.getAbsolutePath())) {
		char[] buff = new char[256];
		int len = 0;
		while ((len = fr.read(buff)) != -1) {
			cw.write(buff, 0, len);
		}
		return cw.toCharArray();
	}
}
 
Example #24
Source File: JavaFile.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
public static List<String> readFileToList(String fileName) throws IOException{
	File file = new File(fileName);
	if(!file.exists()){
		System.out.println("File : " + fileName + " does not exist!");
		return null;
	}
	BufferedReader br = new BufferedReader(new FileReader(file));
	String line = null;
	List<String> source = new ArrayList<>();
	source.add("useless");
	while((line = br.readLine()) != null){
		source.add(line);
	}
	br.close();
	
	return source;
}
 
Example #25
Source File: WholeFile.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void method(int[] array) {
for (int i = 0; i < array.length; i++) {
int j = array[i];            
System.out.println(j);
}
try {
FileReader reader = new FileReader("");
    HashMap hashMap;
    Map map;
    List l;
    LinkedList ll;
    ArrayList al;
           
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
System.out.println("finally");
//close
}
}
 
Example #26
Source File: Universe.java    From L2jBrasil with GNU General Public License v3.0 5 votes vote down vote up
public void loadAscii()
{
    int initialSize = _coordList.size();
    try
    {
        BufferedReader r = new BufferedReader(new FileReader("data/universe.txt"));
        String line;
        while ((line = r.readLine()) != null)
        {
            StringTokenizer st = new StringTokenizer(line);
            String x1 = st.nextToken();
            String y1 = st.nextToken();
            String z1 = st.nextToken();
            //                String f1 = st.nextToken();
            int x = Integer.parseInt(x1);
            int y = Integer.parseInt(y1);
            int z = Integer.parseInt(z1);
            //                int f = Integer.parseInt(f1);
            _coordList.add(new Coord(x, y, z));
        }
        r.close();
        _log.info((_coordList.size() - initialSize) + " additional nodes loaded from text file.");
    }
    catch (Exception e)
    {
        _log.info("could not read text file universe.txt");
    }
}
 
Example #27
Source File: IOUtil.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@NonNull
public String readFile(String path) {
    try {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        return stringBuilder.toString();
    } catch (Exception e) {
        return "";
    }
}
 
Example #28
Source File: TestClass.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws FileNotFoundException {
    String fileFullPath = "D:\\code\\GitRepository\\Code\\java-basic\\jdk5\\src\\main\\java\\cn\\lastwhisper\\jdk5\\feature\\reflect\\TestClass.java";
    JavaDocBuilder builder = new JavaDocBuilder();
    builder.addSource(new FileReader(fileFullPath));

    JavaSource src = builder.getSources()[0];
    String[] imports = src.getImports();

    for (String imp : imports) {
        System.out.println(imp);
    }
}
 
Example #29
Source File: GermanLangSpellChecker.java    From customized-symspell with MIT License 5 votes vote down vote up
private static void loadUniGramFile(File file) throws IOException, SpellCheckException {
  BufferedReader br = new BufferedReader(new FileReader(file));
  String line;
  while ((line = br.readLine()) != null) {
    String[] arr = line.split("\\s+");
    dataHolder1.addItem(new DictionaryItem(arr[0], Double.parseDouble(arr[1]), -1.0));
    dataHolder2.addItem(new DictionaryItem(arr[0], Double.parseDouble(arr[1]), -1.0));
  }
}
 
Example #30
Source File: TestHelper.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
protected static void dumpFile(final PrintStream output, final File file) throws IOException {
    try (Reader rdr = new FileReader(file); BufferedReader reader = new BufferedReader(rdr)) {
        while (true) {
            final String line = reader.readLine();
            if (line == null) {
                break;
            }
            output.println(line);
        }
    }
}