java.io.InputStreamReader Java Examples

The following examples show how to use java.io.InputStreamReader. 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: NightlyOutServiceTest.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @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 #2
Source File: DatabaseUtils.java    From hawkular-apm with 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 #3
Source File: 11917 Do Your Own Homework.java    From UVA with GNU General Public License v3.0 6 votes vote down vote up
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 #4
Source File: EncryptedFileSystemTest.java    From encfs4j with 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 #5
Source File: Exploit.java    From EquationExploit with 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 #6
Source File: SocketClient.java    From hack-root with 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 #7
Source File: PropertiesReaderControl.java    From es6draft with 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 #8
Source File: StreamReader.java    From AndroidRobot with 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 #9
Source File: NetworkConnUtil.java    From RairDemo with 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 #10
Source File: GsonAnimationTest.java    From diozero with 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 #11
Source File: SQLWikiParser.java    From tagme with 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 #12
Source File: Bug482203Test.java    From astor with 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 #13
Source File: AppCallbackHandler.java    From lams with 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 #14
Source File: ShellUtils.java    From Xndroid with 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 #15
Source File: CSVUtils.java    From BLELocalization with 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 #16
Source File: bug8059739.java    From jdk8u-dev-jdk with 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 #17
Source File: OAuth2AuthorizeHelperTest.java    From YiBo with 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 #18
Source File: 10245 The Closest Pair Problem.java    From UVA with GNU General Public License v3.0 6 votes vote down vote up
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 #19
Source File: ProcessExecutor.java    From depan with 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 #20
Source File: SQLOutputImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 File: Cmd.java    From Webhooks with 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 File: ZipFileIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private String getZipFileContent(InputStream inputStream) {
    StringBuilder content = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));) {
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return content.toString();
}
 
Example #23
Source File: LoggingServiceImpl.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
private BufferedReader getReader(String cmdId) {
    return logReaderCache.get(cmdId, key -> {
        try {
            String fileName = getLogFile(cmdId);
            InputStream stream = fileManager.read(fileName, getLogDir(cmdId));
            InputStreamReader streamReader = new InputStreamReader(stream);
            BufferedReader reader = new BufferedReader(streamReader, FileBufferSize);
            reader.mark(1);
            return reader;
        } catch (IOException e) {
            return null;
        }
    });
}
 
Example #24
Source File: PlatformClasses.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static synchronized String[] getNames() {
    if (names == null) {
        LinkedList<String> list = new LinkedList<String>();
        InputStream str
            = PlatformClasses.class
                .getResourceAsStream("/com/sun/tools/hat/resources/platform_names.txt");
        if (str != null) {
            try {
                BufferedReader rdr
                    = new BufferedReader(new InputStreamReader(str));
                for (;;) {
                    String s = rdr.readLine();
                    if (s == null) {
                        break;
                    } else if (s.length() > 0) {
                        list.add(s);
                    }
                }
                rdr.close();
                str.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                // Shouldn't happen, and if it does, continuing
                // is the right thing to do anyway.
            }
        }
        names = list.toArray(new String[list.size()]);
    }
    return names;
}
 
Example #25
Source File: SessionDaoTest.java    From droidkaigi2016 with Apache License 2.0 5 votes vote down vote up
List<Session> loadSessions() {
    try (InputStream is = getContext().getResources().openRawResource(R.raw.sessions_ja)) {
        Gson gson = DroidKaigiClient.createGson();
        Type t = new TypeToken<Collection<Session>>() {
        }.getType();
        return gson.fromJson(new InputStreamReader(is), t);
    } catch (IOException e) {
        throw new AssertionError(e);
    }
}
 
Example #26
Source File: JarDumper.java    From buck with Apache License 2.0 5 votes vote down vote up
private Stream<String> dumpClassFile(InputStream stream) throws IOException {
  byte[] textifiedClass;
  try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
      PrintWriter pw = new PrintWriter(bos)) { // NOPMD required by API
    ClassReader reader = new ClassReader(stream);
    TraceClassVisitor traceVisitor = new TraceClassVisitor(null, new Textifier(), pw);
    reader.accept(traceVisitor, asmFlags);
    textifiedClass = bos.toByteArray();
  }

  try (InputStreamReader streamReader =
      new InputStreamReader(new ByteArrayInputStream(textifiedClass))) {
    return CharStreams.readLines(streamReader).stream();
  }
}
 
Example #27
Source File: GsonHttpMessageReader.java    From validator-web with Apache License 2.0 5 votes vote down vote up
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpServletRequest request)
        throws IOException, HttpMessageNotReadableException {
    
    InputStream in = request.getInputStream();
    return gson.fromJson(new InputStreamReader(in), clazz);
}
 
Example #28
Source File: InputSocket.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws Exception {
  logger.info("Starting socket server (port: {}, protocol: {}, secure: {})", port, protocol, secure);
  ServerSocketFactory socketFactory = secure ? SSLServerSocketFactory.getDefault() : ServerSocketFactory.getDefault();
  InputSocketMarker inputSocketMarker = new InputSocketMarker(this, port, protocol, secure, log4j);
  LogsearchConversion loggerConverter = new LogsearchConversion();

  try {
    serverSocket = socketFactory.createServerSocket(port);
    while (!isDrain()) {
      Socket socket = serverSocket.accept();
      if (log4j) {
        try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()))) {
          LoggingEvent loggingEvent = (LoggingEvent) ois.readObject();
          String jsonStr = loggerConverter.createOutput(loggingEvent);
          logger.trace("Incoming socket logging event: " + jsonStr);
          outputLine(jsonStr, inputSocketMarker);
        }
      } else {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));) {
          String line = in.readLine();
          logger.trace("Incoming socket message: " + line);
          outputLine(line, inputSocketMarker);
        }
      }
    }
  } catch (SocketException socketEx) {
    logger.warn("{}", socketEx.getMessage());
  } finally {
    serverSocket.close();
  }
}
 
Example #29
Source File: StreamUtil.java    From cymbal with Apache License 2.0 5 votes vote down vote up
/**
 * Read Strings to list from InputStream and do log with info level.
 *
 * @param inputStream stream to read
 * @return Strings from stream
 */
public static List<String> toList(final InputStream inputStream, final Logger log) throws IOException {
    List<String> result = new ArrayList<>();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line;
    while (Objects.nonNull(line = bufferedReader.readLine())) {
        result.add(line);
        if (Objects.nonNull(log)) {
            log.info(line);
        }
    }
    return result;
}
 
Example #30
Source File: UNIXTools.java    From Juicebox with 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();
}