Java Code Examples for java.io.FileReader

The following examples show how to use java.io.FileReader. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: SimFix   Source File: JavaFile.java    License: 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 2
Source Project: openjdk-jdk9   Source File: Test8.java    License: 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 3
@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 4
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 5
Source Project: dfactor   Source File: DFActorManagerJs.java    License: 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 Project: metanome-algorithms   Source File: Relation.java    License: 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 7
Source Project: WeiXinRecordedDemo   Source File: VideoEditor.java    License: 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 8
Source Project: JavaRushTasks   Source File: Solution.java    License: 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 9
Source Project: openjdk-jdk8u   Source File: CommandLine.java    License: 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 10
@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 11
Source Project: jdk8u-jdk   Source File: J2DBench.java    License: 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 12
Source Project: OrionAlpha   Source File: ShopApp.java    License: 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 13
Source Project: FirefoxReality   Source File: Windows.java    License: 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 14
Source Project: super-cloudops   Source File: SSH2Holders.java    License: 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 15
Source Project: JCMathLib   Source File: PerfTests.java    License: 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 16
Source Project: netbeans   Source File: WholeFile.java    License: 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 17
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 18
Source Project: opscenter   Source File: FileTreeServiceImpl.java    License: 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 19
Source Project: genesis   Source File: SnippetLoader.java    License: 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 Project: kitty   Source File: FileUtils.java    License: 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 21
Source Project: Flink-CEPplus   Source File: Hardware.java    License: 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 Project: netbeans   Source File: Utils.java    License: 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 23
Source Project: CQL   Source File: AqlCmdLine.java    License: 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 24
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 25
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 26
Source Project: jdk8u-jdk   Source File: Utils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns file content as a list of strings
 *
 * @param file File to operate on
 * @return List of strings
 * @throws IOException
 */
public static List<String> fileAsList(File file) throws IOException {
    assertTrue(file.exists() && file.isFile(),
            file.getAbsolutePath() + " does not exist or not a file");
    List<String> output = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(file.getAbsolutePath()))) {
        while (reader.ready()) {
            output.add(reader.readLine().replace(NEW_LINE, ""));
        }
    }
    return output;
}
 
Example 27
Source Project: o2oa   Source File: Exit.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private static List<String> readManifest(File file) throws Exception {
	List<String> list = new ArrayList<>();
	try (FileReader fileReader = new FileReader(file);
			BufferedReader bufferedReader = new BufferedReader(fileReader)) {
		String line;
		while ((line = bufferedReader.readLine()) != null) {
			list.add(line);
		}
	}
	return list;
}
 
Example 28
Source Project: component-runtime   Source File: ValidateDependencies.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertDependencies() throws IOException {
    final File dependenciesTxt = new File(jarLocation(ValidateDependencies.class), "TALEND-INF/dependencies.txt");
    assertTrue(dependenciesTxt.exists());
    try (final BufferedReader reader = new BufferedReader(new FileReader(dependenciesTxt))) {
        assertEquals("", reader.lines().collect(joining("\n")));
    }
}
 
Example 29
Source Project: submarine   Source File: ExperimentRestApiIT.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startUp() throws IOException {
  Assert.assertTrue(checkIfServerIsRunning());

  // The kube config path defined by kind-cluster-build.sh
  String confPath = System.getProperty("user.home") + "/.kube/kind-config-kind";
  KubeConfig config = KubeConfig.loadKubeConfig(new FileReader(confPath));
  ApiClient client = ClientBuilder.kubeconfig(config).build();
  Configuration.setDefaultApiClient(client);
  k8sApi = new CustomObjectsApi();

  kfOperatorMap = new HashMap<>();
  kfOperatorMap.put("tensorflow", new KfOperator("v1", "tfjobs"));
  kfOperatorMap.put("pytorch", new KfOperator("v1", "pytorchjobs"));
}
 
Example 30
@Test
public void testIterability() throws Exception {
	Instances data = new Instances(new FileReader(this.dataset));
	data.setClassIndex(data.numAttributes() - 1);
	WekaInstances wrapped = new WekaInstances(data);
	for (IWekaInstance wi : wrapped) {
		assertTrue(data.contains(wi.getElement()));
	}
}