Java源码示例:java.io.InputStreamReader
示例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");
}
}
示例2
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
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
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
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
@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
@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
@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
@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
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
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
/**
* @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
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
/**
* 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
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
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
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
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
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
/**
* 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
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
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
/**
* 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
/**
* 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
/**
* 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
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
@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
@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
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
@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);
}