类java.io.InputStreamReader源码实例Demo

下面列出了怎么用java.io.InputStreamReader的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: UVA   文件: 10245 The Closest Pair Problem.java
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");
	}
}
 
源代码2 项目: BLELocalization   文件: CSVUtils.java
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;
}
 
源代码3 项目: Xndroid   文件: ShellUtils.java
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();
    }
}
 
源代码4 项目: tagme   文件: SQLWikiParser.java
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();
	
}
 
源代码5 项目: diozero   文件: GsonAnimationTest.java
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);
	}
}
 
源代码6 项目: es6draft   文件: PropertiesReaderControl.java
@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);
}
 
源代码7 项目: encfs4j   文件: EncryptedFileSystemTest.java
@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());
}
 
源代码8 项目: YiBo   文件: OAuth2AuthorizeHelperTest.java
@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);
}
 
源代码9 项目: depan   文件: ProcessExecutor.java
@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;
    }
  }
}
 
源代码10 项目: astor   文件: Bug482203Test.java
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();
    }
}
 
源代码11 项目: jdk8u-dev-jdk   文件: bug8059739.java
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);
        }
    }
}
 
源代码12 项目: kfs   文件: NightlyOutServiceTest.java
/**
 * @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;
}
 
源代码13 项目: EquationExploit   文件: Exploit.java
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;
}
 
源代码14 项目: hawkular-apm   文件: DatabaseUtils.java
/**
 * 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);
    }
}
 
源代码15 项目: UVA   文件: 11917 Do Your Own Homework.java
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");
	}
}
 
源代码16 项目: hack-root   文件: SocketClient.java
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();
    }
}
 
源代码17 项目: AndroidRobot   文件: StreamReader.java
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();
    	}
    }
 
源代码18 项目: RairDemo   文件: NetworkConnUtil.java
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;
}
 
源代码19 项目: lams   文件: AppCallbackHandler.java
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;
}
 
源代码20 项目: openjdk-8-source   文件: SQLOutputImpl.java
/**
 * 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());
    }
}
 
源代码21 项目: Webhooks   文件: Cmd.java
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;
}
 
源代码22 项目: Juicebox   文件: UNIXTools.java
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();
}
 
源代码23 项目: oslib   文件: Utils.java
/**
 * 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;
}
 
源代码24 项目: dumbster   文件: SimpleSmtpServer.java
/**
 * 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);
			}
		}
	}
}
 
源代码25 项目: Tok-Android   文件: FileUtilsJ.java
/**
 * 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();
}
 
源代码26 项目: seed   文件: WkhtmltopdfUtil.java
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);
    }
}
 
源代码27 项目: baleen   文件: SharedGenderMultiplicityResource.java
@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);
}
 
源代码28 项目: jeesuite-config   文件: LocalCacheUtils.java
@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;
}
 
源代码29 项目: ZKRecipesByExample   文件: PathCacheExample.java
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 {

	}
}
 
源代码30 项目: proctor   文件: ClasspathProctorLoader.java
@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);
}
 
 类所在包
 同包方法