Java Code Examples for java.io.InputStreamReader

The following examples show how to use java.io.InputStreamReader. 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
public static void main (String [] args) throws Exception {
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	String s;
	while (!(s=br.readLine()).equals("0")) {
		int N=Integer.parseInt(s);
		double [][] points=new double [N][];
		for (int n=0;n<N;n++) {
			StringTokenizer st=new StringTokenizer(br.readLine());
			points[n]=new double [] {Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())};
		}
		double min=Double.MAX_VALUE;
		for (int n=0;n<N;n++) for (int n2=n+1;n2<N;n2++) {
			double dx=points[n][0]-points[n2][0];
			double dy=points[n][1]-points[n2][1];
			double dist=Math.sqrt(dx*dx+dy*dy);
			if (min>dist) min=dist;
		}
		
		if (min<10000) System.out.printf("%.4f\n", min);
		else System.out.println("INFINITY");
	}
}
 
Example 2
Source Project: BLELocalization   Source File: CSVUtils.java    License: MIT License 6 votes vote down vote up
static String[][] readCSVasStrings(InputStream is){
	Reader in = new InputStreamReader(is);
	BufferedReader br = new BufferedReader(in);

	List<String[]> stringsList = new ArrayList<String[]>();
	String line = null;
	try {
		while( (line=br.readLine()) != null ){
			String[] tokens = line.split(",");
			stringsList.add(tokens);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
	String[][] strings = stringsList.toArray(new String[0][]);
	return strings;
}
 
Example 3
Source Project: Xndroid   Source File: ShellUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void checkRoot() {
    sRoot = false;
    char[] buff = new char[1024];
    try {
        Process process = Runtime.getRuntime().exec("su");
        OutputStreamWriter output = new OutputStreamWriter(process.getOutputStream());
        InputStreamReader input = new InputStreamReader(process.getInputStream());
        String testStr = "ROOT_TEST";
        output.write("echo " + testStr + "\n");
        output.flush();
        output.write("exit\n");
        output.flush();
        process.waitFor();
        int count = input.read(buff);
        if (count > 0) {
            if (new String(buff, 0, count).startsWith(testStr))
                sRoot = true;
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}
 
Example 4
Source Project: tagme   Source File: SQLWikiParser.java    License: Apache License 2.0 6 votes vote down vote up
public void compute(InputStreamReader in) throws IOException
{
	if (log != null) log.start();
	int i = in.read();
	while(i > 0)
	{
		String firstToken = readToken(in);
		if (firstToken.equals("INSERT"))
		{
			ArrayList<String> values = null;
			while ((values=readValues(in)) != null)
			{
				if (log != null) log.update(0);
				boolean proc = compute(values);
				if (log != null && proc) log.update(1);
			}
		}
		else
			i = readEndLine(in);
	}
	finish();
	
}
 
Example 5
Source Project: diozero   Source File: GsonAnimationTest.java    License: MIT License 6 votes vote down vote up
private static void animate(Collection<OutputDeviceInterface> targets, int fps, EasingFunction easing, float speed,
		String... files) throws IOException {
	Animation anim = new Animation(targets, fps, easing, speed);

	Gson gson = new Gson();
	for (String file : files) {
		try (Reader reader = new InputStreamReader(GsonAnimationTest.class.getResourceAsStream(file))) {
			AnimationInstance anim_obj = gson.fromJson(reader, AnimationInstance.class);

			anim.enqueue(anim_obj);
		}
	}
	
	Logger.info("Starting animation...");
	Future<?> future = anim.play();
	try {
		Logger.info("Waiting");
		future.get();
		Logger.info("Finished");
	} catch (CancellationException | ExecutionException | InterruptedException e) {
		Logger.info("Finished {}", e);
	}
}
 
Example 6
Source Project: es6draft   Source File: PropertiesReaderControl.java    License: MIT License 6 votes vote down vote up
@Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
        throws IOException {
    if ("java.properties".equals(format)) {
        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, "properties");
        InputStream stream = getInputStream(loader, resourceName, reload);
        if (stream == null) {
            return null;
        }
        try (Reader reader = new InputStreamReader(stream, charset)) {
            return new PropertyResourceBundle(reader);
        }
    }
    throw new IllegalArgumentException("unknown format: " + format);
}
 
Example 7
Source Project: encfs4j   Source File: EncryptedFileSystemTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSyntaxB() throws IOException {

	Path path = Paths.get(URI.create("enc:///"
			+ persistentFile.getAbsolutePath().replaceAll("\\\\", "/")));
	if (!Files.exists(path)) {
		Files.createFile(path);
	}

	OutputStream outStream = Files.newOutputStream(path);
	outStream.write(testString.getBytes());
	outStream.close();

	InputStream inStream = Files.newInputStream(path);
	BufferedReader in = new BufferedReader(new InputStreamReader(inStream));

	StringBuilder buf = new StringBuilder();
	String line = null;
	while ((line = in.readLine()) != null) {
		buf.append(line);
	}
	inStream.close();

	assertEquals(testString, buf.toString());
}
 
Example 8
Source Project: YiBo   Source File: OAuth2AuthorizeHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testImplicitGrant() {
	Authorization auth = new Authorization(TokenConfig.currentProvider);
	try {
		OAuth2AuthorizeHelper oauthHelper = new OAuth2AuthorizeHelper();
		String authorzieUrl = oauthHelper.getAuthorizeUrl(auth, GrantType.IMPLICIT, DisplayType.PC);
		BareBonesBrowserLaunch.openURL(authorzieUrl);
		String url = null;
		while (null == url || url.trim().length() == 0) {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("Please Enter implicit Callback : ");
			url = br.readLine();
		}
		
		auth = OAuth2AuthorizeHelper.retrieveAccessTokenFromFragment(url);
		
	} catch (Exception e) {
		e.printStackTrace();
		auth = null;
	}
	
	assertNotNull(auth);
}
 
Example 9
Source Project: depan   Source File: ProcessExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  Reader reader = new InputStreamReader(input);
  boolean ready = true;
  while (ready) {
    try {
      // It's OK if this blocks until a character is ready.
      int next = reader.read();
      if (next < 0) {
        ready = false;
      } else {
        result.append((char) next);
      }
    } catch (IOException e) {
      ready = false;
    }
  }
}
 
Example 10
Source Project: astor   Source File: Bug482203Test.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void testJsApi() throws Exception {
    Context cx = Context.enter();
    try {
        cx.setOptimizationLevel(-1);
        Script script = cx.compileReader(new InputStreamReader(
                Bug482203Test.class.getResourceAsStream("Bug482203.js")),
                "", 1, null);
        Scriptable scope = cx.initStandardObjects();
        script.exec(cx, scope);
        int counter = 0;
        for(;;)
        {
            Object cont = ScriptableObject.getProperty(scope, "c");
            if(cont == null)
            {
                break;
            }
            counter++;
            ((Callable)cont).call(cx, scope, scope, new Object[] { null });
        }
        assertEquals(counter, 5);
        assertEquals(Double.valueOf(3), ScriptableObject.getProperty(scope, "result"));
    } finally {
        Context.exit();
    }
}
 
Example 11
Source Project: jdk8u-dev-jdk   Source File: bug8059739.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void runTest() throws Exception {
    String testString = "my string";
    JTextField tf = new JTextField(testString);
    tf.selectAll();
    Clipboard clipboard = new Clipboard("clip");
    tf.getTransferHandler().exportToClipboard(tf, clipboard, TransferHandler.COPY);
    DataFlavor[] dfs = clipboard.getAvailableDataFlavors();
    for (DataFlavor df: dfs) {
        String charset = df.getParameter("charset");
        if (InputStream.class.isAssignableFrom(df.getRepresentationClass()) &&
                charset != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (InputStream) clipboard.getData(df), charset));
            String s = br.readLine();
            System.out.println("Content: '" + s + "'");
            passed &= s.contains(testString);
        }
    }
}
 
Example 12
/**
 * @return the number of entries in the nightly out origin entry file
 */
protected int countOriginEntriesInFile() {
    int count = 0;
    try {
        File nightlyOutFile = new File(this.nightlyOutFileName);
        BufferedReader nightlyOutFileIn = new BufferedReader(new InputStreamReader(new FileInputStream(nightlyOutFile)));
        while (nightlyOutFileIn.readLine() != null) {
            count += 1;
        }
    }
    catch (FileNotFoundException fnfe) {
        //let's not sweat this one - if the file didn't exist, we'd hit errors before this
        throw new RuntimeException(fnfe);
    }
    catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
    return count;
}
 
Example 13
Source Project: EquationExploit   Source File: Exploit.java    License: MIT License 6 votes vote down vote up
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;
}
 
Example 14
Source Project: hawkular-apm   Source File: DatabaseUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads SQL statements from file. SQL commands in file must be separated by
 * a semicolon.
 *
 * @param url url of the file
 * @return array of command  strings
 */
private static String[] readSqlStatements(URL url) {
    try {
        char buffer[] = new char[256];
        StringBuilder result = new StringBuilder();
        InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF-8");
        while (true) {
            int count = reader.read(buffer);
            if (count < 0) {
                break;
            }
            result.append(buffer, 0, count);
        }
        return result.toString().split(";");
    } catch (IOException ex) {
        throw new RuntimeException("Cannot read " + url, ex);
    }
}
 
Example 15
public static void main (String [] args) throws Exception {
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	int testCaseCount=Integer.parseInt(br.readLine());
	for (int testCase=1;testCase<=testCaseCount;testCase++) {
		int c=Integer.parseInt(br.readLine());
		HashMap<String,Integer> map=new HashMap<>();
		for (int i=0;i<c;i++) {
			StringTokenizer st=new StringTokenizer(br.readLine());
			map.put(st.nextToken(), Integer.parseInt(st.nextToken()));
		}
		int d=Integer.parseInt(br.readLine());
		String target=br.readLine();
		if (!map.containsKey(target) || map.get(target)>d+5) System.out.println("Case "+testCase+": Do your own homework!");
		else if (map.get(target)>d) System.out.println("Case "+testCase+": Late");
		else System.out.println("Case "+testCase+": Yesss");
	}
}
 
Example 16
Source Project: hack-root   Source File: SocketClient.java    License: MIT License 6 votes vote down vote up
private void readServerData(final Socket socket) {
    try {
        InputStreamReader ipsReader = new InputStreamReader(socket.getInputStream());
        BufferedReader bfReader = new BufferedReader(ipsReader);
        String line = null;
        while ((line = bfReader.readLine()) != null) {
            Log.d(TAG, "client receive: " + line);
            listener.onMessage(line);
        }
        ipsReader.close();
        bfReader.close();
        printWriter.close();
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 17
Source Project: AndroidRobot   Source File: StreamReader.java    License: Apache License 2.0 6 votes vote down vote up
public void run(){
    	try{
    		InputStreamReader isr = new InputStreamReader(is,"UTF-8");
    		BufferedReader br = new BufferedReader(isr);
    		
    		String line=null;
    		while ( (line = br.readLine()) != null && running)
    		{
//    			System.out.println(line+"\n");
    			this.appendStringBuffer(line+"\n");
    		}
    		
    		System.out.println("=================="+" end "+"====================\n");

    	}catch(IOException e){
    		e.printStackTrace();
    	}
    }
 
Example 18
Source Project: RairDemo   Source File: NetworkConnUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String callCmd(String cmd, String filter) {
    String result = "";
    String line = "";
    try {
        Process proc = Runtime.getRuntime().exec(cmd);
        InputStreamReader is = new InputStreamReader(proc.getInputStream());
        BufferedReader br = new BufferedReader(is);

        // 执行命令cmd,只取结果中含有filter的这一行
        while ((line = br.readLine()) != null
                && line.contains(filter) == false) {
        }

        result = line;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 19
Source Project: lams   Source File: AppCallbackHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
private String getUserNameFromConsole(String prompt)
{
   String uName = "";
   System.out.print(prompt);
   InputStreamReader isr = new InputStreamReader(System.in);
   BufferedReader br = new BufferedReader(isr);
   try
   {
      uName = br.readLine(); 
   }
   catch(IOException e)
   {
      throw PicketBoxMessages.MESSAGES.failedToObtainUsername(e);
   }
   return uName;
}
 
Example 20
/**
 * Writes a stream of ASCII characters to this
 * <code>SQLOutputImpl</code> object. The driver will do any necessary
 * conversion from ASCII to the database <code>CHAR</code> format.
 *
 * @param x the value to pass to the database
 * @throws SQLException if the <code>SQLOutputImpl</code> object is in
 *        use by a <code>SQLData</code> object attempting to write the attribute
 *        values of a UDT to the database.
 */
@SuppressWarnings("unchecked")
public void writeAsciiStream(java.io.InputStream x) throws SQLException {
     BufferedReader bufReader = new BufferedReader(new InputStreamReader(x));
     try {
           int i;
           while( (i=bufReader.read()) != -1 ) {
            char ch = (char)i;

            StringBuffer strBuf = new StringBuffer();
            strBuf.append(ch);

            String str = new String(strBuf);
            String strLine = bufReader.readLine();

            writeString(str.concat(strLine));
        }
      }catch(IOException ioe) {
        throw new SQLException(ioe.getMessage());
    }
}
 
Example 21
Source Project: Webhooks   Source File: Cmd.java    License: Apache License 2.0 6 votes vote down vote up
public static String execLinuxCmd(String cmd) {
    try {
        String[] cmdA = {"/bin/sh", "-c", cmd};
        Process process = Runtime.getRuntime().exec(cmdA);
        LineNumberReader br = new LineNumberReader(new InputStreamReader(
                process.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        br.close();
        process.getOutputStream().close(); // 不要忘记了一定要关
        return sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 22
Source Project: Juicebox   Source File: UNIXTools.java    License: MIT License 5 votes vote down vote up
private static String executeComplexCommand(List<String> command) {
    StringBuilder output = new StringBuilder();

    //System.out.println(System.getenv());

    ProcessBuilder b = new ProcessBuilder(command);
    //Map<String, String> env = b.environment();
    //System.out.println(env);

    Process p;
    try {
        //p = Runtime.getRuntime().exec(command);
        p = b.redirectErrorStream(true).start();

        if (HiCGlobals.printVerboseComments) {
            System.out.println("Command exec " + p.waitFor());
        } else {
            p.waitFor();
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()), HiCGlobals.bufferSize);

        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return output.toString();
}
 
Example 23
Source Project: oslib   Source File: Utils.java    License: MIT License 5 votes vote down vote up
/**
 * Runs the command "uname -a" and reads the first line
 */
public static String getUname() {
    String uname = null;

    try {
        Process p = Runtime.getRuntime().exec(new String[]{"uname", "-a"});
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        uname = reader.readLine();
        reader.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return uname;
}
 
Example 24
Source Project: dumbster   Source File: SimpleSmtpServer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Main loop of the SMTP server.
 */
private void performWork() {
	try {
		// Server: loop until stopped
		while (!stopped) {
			// Start server socket and listen for client connections
			//noinspection resource
			try (Socket socket = serverSocket.accept();
			     Scanner input = new Scanner(new InputStreamReader(socket.getInputStream(), StandardCharsets.ISO_8859_1)).useDelimiter(CRLF);
			     PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.ISO_8859_1));) {

				synchronized (receivedMail) {
					/*
					 * We synchronize over the handle method and the list update because the client call completes inside
					 * the handle method and we have to prevent the client from reading the list until we've updated it.
					 */
					receivedMail.addAll(handleTransaction(out, input));
				}
			}
		}
	} catch (Exception e) {
		// SocketException expected when stopping the server
		if (!stopped) {
			log.error("hit exception when running server", e);
			try {
				serverSocket.close();
			} catch (IOException ex) {
				log.error("and one when closing the port", ex);
			}
		}
	}
}
 
Example 25
Source Project: Tok-Android   Source File: FileUtilsJ.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * read String from inputStream
 *
 * @throws Exception
 */
private static String readTextFromSDcard(InputStream is) throws Exception {
    InputStreamReader reader = new InputStreamReader(is);
    BufferedReader bufferedReader = new BufferedReader(reader);
    StringBuffer buffer = new StringBuffer("");
    String str;
    while ((str = bufferedReader.readLine()) != null) {
        buffer.append(str);
        buffer.append("\n");
    }
    return buffer.toString();
}
 
Example 26
Source Project: seed   Source File: WkhtmltopdfUtil.java    License: Apache License 2.0 5 votes vote down vote up
public void run() {
    try{
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        for(String line; (line=br.readLine())!=null;){
            LogUtil.getLogger().info(line);
        }
    }catch(Exception e){
        throw new RuntimeException(e);
    }
}
 
Example 27
Source Project: baleen   Source File: SharedGenderMultiplicityResource.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doInitialize(ResourceSpecifier specifier, Map<String, Object> additionalParams)
    throws ResourceInitializationException {

  Arrays.asList(
          "gender.aa.gz",
          "gender.ab.gz",
          "gender.ac.gz",
          "gender.ad.gz",
          "gender.ae.gz",
          "gender.af.gz")
      .stream()
      .flatMap(
          f -> {
            try (BufferedReader reader =
                new BufferedReader(
                    new InputStreamReader(
                        new GZIPInputStream(getClass().getResourceAsStream("gender/" + f)),
                        StandardCharsets.UTF_8))) {
              // Crazy, but if we return then the inputstream gets closed so the lines()
              // stream fails.
              return reader.lines().collect(Collectors.toList()).stream();
            } catch (final Exception e) {
              getMonitor().warn("Unable to load from gender file", e);
              return Stream.empty();
            }
          })
      .filter(s -> s.contains("\t"))
      // TODO; Currently ignore any of the numerical stuff its too tedious to work with
      .filter(s -> !s.contains("#"))
      .forEach(this::loadFromGenderRow);

  return super.doInitialize(specifier, additionalParams);
}
 
Example 28
Source Project: jeesuite-config   Source File: LocalCacheUtils.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Map<String, Object> read() {
	try {
		File dir = new File(localStorageDir);
		if (!dir.exists())
			dir.mkdirs();
		File file = new File(dir, "config-cache.json");
		if (!file.exists()) {
			return null;
		}

		StringBuilder buffer = new StringBuilder();
		InputStream is = new FileInputStream(file);
		String line;
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		line = reader.readLine();
		while (line != null) { 
			buffer.append(line); 
			line = reader.readLine();
		}
		reader.close();
		is.close();
		return JsonUtils.toObject(buffer.toString(), Map.class);
	} catch (Exception e) {
		
	}
	return null;
}
 
Example 29
Source Project: ZKRecipesByExample   Source File: PathCacheExample.java    License: Apache License 2.0 5 votes vote down vote up
private static void processCommands(CuratorFramework client, PathChildrenCache cache) throws Exception {
	// More scaffolding that does a simple command line processor
	printHelp();
	try {
		addListener(cache);
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		boolean done = false;
		while (!done) {
			System.out.print("> ");
			String line = in.readLine();
			if (line == null) {
				break;
			}
			String command = line.trim();
			String[] parts = command.split("\\s");
			if (parts.length == 0) {
				continue;
			}
			String operation = parts[0];
			String args[] = Arrays.copyOfRange(parts, 1, parts.length);
			if (operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?")) {
				printHelp();
			} else if (operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit")) {
				done = true;
			} else if (operation.equals("set")) {
				setValue(client, command, args);
			} else if (operation.equals("remove")) {
				remove(client, command, args);
			} else if (operation.equals("list")) {
				list(cache);
			}
			Thread.sleep(1000); // just to allow the console output to catch
								// up
		}
	} finally {

	}
}
 
Example 30
Source Project: proctor   Source File: ClasspathProctorLoader.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected TestMatrixArtifact loadTestMatrix() throws IOException, MissingTestMatrixException {
    final InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
    if (resourceAsStream == null) {
        throw new MissingTestMatrixException("Could not load proctor test matrix from classpath: " + resourcePath);
    }
    final Reader reader = new InputStreamReader(resourceAsStream);
    return loadJsonTestMatrix(reader);
}