下面列出了java.io.DataInputStream#readLine ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static ArrayList<String> nativeGetConnectedIP(String deviceName) {
ArrayList<String> connectedIP = new ArrayList<String>();
try {
Process local=Runtime.getRuntime().exec("cat /proc/net/arp");
DataInputStream os=new DataInputStream(local.getInputStream());
String line;
Log.i(TAG,"arp begin");
while ((line = os.readLine()) != null) {
Log.i(TAG, line);
String[] splited = line.split("\\s+");
if (splited != null && splited.length > 5) {
if(!splited[3].equals("00:00:00:00:00:00")&&splited[5].contains(deviceName)){
String ip = splited[0];
connectedIP.add(ip);
}
}
}
Log.i(TAG,"arp end");
} catch (IOException e) {
e.printStackTrace();
}
// connectedIP.remove(0);
return connectedIP;
}
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException
{
RSA rsa = new RSA();
DataInputStream in = new DataInputStream(System.in);
String teststring;
System.out.println("Enter the plain text:");
teststring = in.readLine();
System.out.println("Encrypting String: " + teststring);
System.out.println("String in Bytes: "
+ bytesToString(teststring.getBytes()));
// encrypt
byte[] encrypted = rsa.encrypt(teststring.getBytes());
// decrypt
byte[] decrypted = rsa.decrypt(encrypted);
System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted String: " + new String(decrypted));
}
private String getStreamLines(final InputStream is) {
String out = null;
StringBuffer buffer = null;
final DataInputStream dis = new DataInputStream(is);
try {
if (dis.available() > 0) {
buffer = new StringBuffer(dis.readLine());
while (dis.available() > 0) {
buffer.append("\n").append(dis.readLine());
}
}
dis.close();
} catch (final Exception ex) {
Log.e(TAG, ex.getMessage());
}
if (buffer != null) {
out = buffer.toString();
}
return out;
}
/**
* 读取所有行
*
* @param reader 读取器
* @return 所有行的列表
*/
@SuppressWarnings("deprecation")
public static ArrayList<String> readOtherInfo(DataInputStream reader)
{
ArrayList<String> result = new ArrayList<>();
while (true)
{
try
{
String line = reader.readLine();
if (line.isEmpty())
{
break;
}
result.add(line);
}
catch (IOException e)
{
e.printStackTrace();
break;
}
}
return result;
}
/**
* Create a new Event Reader
* @param in
* @throws IOException
*/
@SuppressWarnings("deprecation")
public EventReader(DataInputStream in) throws IOException {
this.in = in;
this.version = in.readLine();
if (!EventWriter.VERSION.equals(version)) {
throw new IOException("Incompatible event log version: "+version);
}
Schema myschema = new SpecificData(Event.class.getClassLoader()).getSchema(Event.class);
this.schema = Schema.parse(in.readLine());
this.reader = new SpecificDatumReader(schema, myschema);
this.decoder = DecoderFactory.get().jsonDecoder(schema, in);
}
private String api_call(String endpoint, List<P<String, String>> data) {
StringBuilder postData = new StringBuilder();
try {
URL url = new URL(endpoint);
for (P<String,String> param : data) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.fst(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.snd()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
DataInputStream in = new DataInputStream(conn.getInputStream());
String resp = "", line;
while ( (line = in.readLine()) != null) {
resp += line;
}
return resp;
} catch (IOException e) {
System.out.println("ChemSpider: SHOULD NOT HAPPEN: Failed API call: " + e.getMessage() + " on data: " + postData);
return "";
}
}
/**
* Create a new Event Reader
* @param in
* @throws IOException
*/
@SuppressWarnings("deprecation")
public EventReader(DataInputStream in) throws IOException {
this.in = in;
this.version = in.readLine();
if (!EventWriter.VERSION.equals(version)) {
throw new IOException("Incompatible event log version: "+version);
}
Schema myschema = new SpecificData(Event.class.getClassLoader()).getSchema(Event.class);
this.schema = Schema.parse(in.readLine());
this.reader = new SpecificDatumReader(schema, myschema);
this.decoder = DecoderFactory.get().jsonDecoder(schema, in);
}
@SuppressWarnings( {"rawtypes", "deprecation"})
@Override
public void parse(InputStream is) throws Exception {
int eventCtr = 0;
try {
final long start = System.currentTimeMillis();
DataInputStream in = new DataInputStream(is);
String version = in.readLine();
if (!"Avro-Json".equals(version)) {
throw new IOException("Incompatible event log version: " + version);
}
Schema schema = Schema.parse(in.readLine());
SpecificDatumReader datumReader = new SpecificDatumReader(schema);
JsonDecoder decoder = DecoderFactory.get().jsonDecoder(schema, in);
Event wrapper;
while ((wrapper = getNextEvent(datumReader, decoder)) != null) {
++eventCtr;
reader.handleEvent(wrapper);
}
reader.parseConfiguration();
// don't need put to finally as it's a kind of flushing data
reader.close();
logger.info("reader used " + (System.currentTimeMillis() - start) + "ms");
} catch (Exception ioe) {
logger.error("Caught exception parsing history file after " + eventCtr + " events", ioe);
throw ioe;
} finally {
if (is != null) {
is.close();
}
}
}
public static String execRootCmd(String cmd) {
String result = "result : ";
try {
Process p = Runtime.getRuntime().exec("su ");
OutputStream outStream = p.getOutputStream();
DataOutputStream dOutStream = new DataOutputStream(outStream);
InputStream inStream = p.getInputStream();
DataInputStream dInStream = new DataInputStream(inStream);
String str1 = String.valueOf(cmd);
String str2 = str1 + "\n";
dOutStream.writeBytes(str2);
dOutStream.flush();
String str3 = null;
String line = "";
while ((line = dInStream.readLine()) != null) {
Log.d("result", str3);
str3 += line;
}
dOutStream.writeBytes("exit\n");
dOutStream.flush();
p.waitFor();
return result;
} catch (Exception e) {
e.printStackTrace();
return result;
}
}
/**
* Load parameters from parameter file.
* @param in Parameter file input stream.
* @throws Exception
*/
public void load(DataInputStream in) throws Exception {
// create variable to save parameters
HashMap<String, String> conf = new HashMap<String, String>();
// read parameter file and parse each line.
// lines started with "//" are considered to be comments
String line = null;
while ((line = in.readLine()) != null) {
line = line.trim();
if (line.startsWith("//") || line.length() == 0) {
continue;
}
StringTokenizer st = new StringTokenizer(line, "= ;");
conf.put(st.nextToken(), st.nextToken());
}
// parameters for experimental setup
language = conf.get("language");
dataType = conf.get("dataType");
// parameters to boost word tf
boostRateNormalWord = Double.parseDouble(conf.get("boostRateNormalWord"));
boostRateMainKeyword = Double.parseDouble(conf.get("boostRateMainKeyword"));
boostRateNormalKeyword = Double.parseDouble(conf.get("boostRateNormalKeyword"));
// parameters to filter documents
minDocKeywordSize = Integer.parseInt(conf.get("minDocKeywordSize"));
// parameters to filter keyword graph nodes
minNodeDF = Integer.parseInt(conf.get("minNodeDF"));
maxNodeDFPercent = Double.parseDouble(conf.get("maxNodeDFPercent"));
// parameters to filter keyword graph edges
minEdgeDF = Integer.parseInt(conf.get("minEdgeDF"));
minEdgeCorrelation = Double.parseDouble(conf.get("minEdgeCorrelation"));
// parameters to detect keyword graph communities
communityDetectAlg = conf.get("communityDetectAlg");
// parameters to split or filter keyword graphs
maxClusterNodeSize = Integer.parseInt(conf.get("maxClusterNodeSize"));
minClusterNodeSize = Integer.parseInt(conf.get("minClusterNodeSize"));
minIntersectPercentToMergeCluster = Double.parseDouble(conf.get("minIntersectPercentToMergeCluster"));
minCpToDuplicateEdge = Double.parseDouble(conf.get("minCpToDuplicateEdge"));
// parameters to assign document to keyword graphs
minSimDoc2KeyGraph = Double.parseDouble(conf.get("minSimDoc2KeyGraph"));
// parameters to filter document clusters
minTopicSize = Integer.parseInt(conf.get("minTopicSize"));
// parameters to processing document clusters
useDocumentTopic = Boolean.parseBoolean(conf.get("useDocumentTopic"));
useDocumentTitleCommonWords = Boolean.parseBoolean(conf.get("useDocumentTitleCommonWords"));
minTitleCommonWordsSize = Integer.parseInt(conf.get("minTitleCommonWordsSize"));
minTitleCommonWordsPercent = Double.parseDouble(conf.get("minTitleCommonWordsPercent"));
fStopwords = conf.get("fStopwords");
stopwords = NlpUtils.importStopwords(fStopwords, language);
eventSplitAlg = conf.get("eventSplitAlg");
// parameters to merge new documents wit stories
minKeygraphCompatibilityDc2St = Double.parseDouble(conf.get("minKeygraphCompatibilityDc2St"));
minCompatibilityDc2Sn = Double.parseDouble(conf.get("minCompatibilityDc2Sn"));
minTFCosineSimilarityDc2Sn = Double.parseDouble(conf.get("minTFCosineSimilarityDc2Sn"));
deltaTimeGap = Double.parseDouble(conf.get("deltaTimeGap"));
deltaDocDistribution = Double.parseDouble(conf.get("deltaDocDistribution"));
// parameters for filter corpora
historyLength = Integer.parseInt(conf.get("historyLength"));
// parameters related to event classification supervised learning
fModel = conf.get("fModel");
model = libsvm.svm.svm_load_model(fModel);
fSameStoryModel = conf.get("fSameStoryModel");
sameStoryModel = libsvm.svm.svm_load_model(fSameStoryModel);
// parameters for query doc matching
useRelatedNewsTitlesForMatch = Boolean.parseBoolean(conf.get("useRelatedNewsTitlesForMatch"));
fQueryDocMatchModel = conf.get("fQueryDocMatchModel");
queryDocMatchModel = libsvm.svm.svm_load_model(fQueryDocMatchModel);
maxMatchedDocsSize = Integer.parseInt(conf.get("maxMatchedDocsSize"));
}
public static boolean canRunRootCommands() {
boolean retval;
Process suProcess;
try {
suProcess = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
DataInputStream osRes = new DataInputStream(suProcess.getInputStream());
// Getting the id of the current user to check if this is root
os.writeBytes("id\n");
os.flush();
String currUid = osRes.readLine();
boolean exitSu;
if (null == currUid) {
retval = false;
exitSu = false;
Log.d("ROOT", "Can't get root access or denied by user");
} else if (currUid.contains("uid=0")) {
retval = true;
exitSu = true;
Log.d("ROOT", "Root access granted");
} else {
retval = false;
exitSu = true;
Log.d("ROOT", "Root access rejected: " + currUid);
}
if (exitSu) {
os.writeBytes("exit\n");
os.flush();
}
} catch (Exception e) {
// Can't get root !
// Probably broken pipe exception on trying to write to output stream (os) after su failed, meaning that the device is not rooted
retval = false;
Log.d("ROOT", "Root access rejected [" + e.getClass().getName() + "] : " + e.getMessage());
}
return retval;
}
/**
* from v7
* <p>
* Use RootManager or other entity created for this effect in the engine
*/
@Deprecated public static boolean hasRoot() {
boolean retval;
Process suProcess;
try {
suProcess = Runtime.getRuntime()
.exec("su");
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
DataInputStream osRes = new DataInputStream(suProcess.getInputStream());
// Getting the id of the current user to check if this is root
os.writeBytes("id\n");
os.flush();
String currUid = osRes.readLine();
boolean exitSu;
if (null == currUid) {
retval = false;
exitSu = false;
Logger.getInstance()
.d("ROOT", "Can't get root access or denied by user");
} else if (currUid.contains("uid=0")) {
retval = true;
exitSu = true;
Logger.getInstance()
.d("ROOT", "Root access granted");
} else {
retval = false;
exitSu = true;
Logger.getInstance()
.d("ROOT", "Root access rejected: " + currUid);
}
if (exitSu) {
os.writeBytes("exit\n");
os.flush();
}
} catch (Exception e) {
// Can't get root !
// Probably broken pipe exception on trying to write to output stream (os) after su failed, meaning that the device is not rooted
retval = false;
Logger.getInstance()
.d("ROOT", "Root access rejected [" + e.getClass()
.getName() + "] : " + e.getMessage());
}
return retval;
}
@SuppressWarnings("deprecation")
private static byte[] readBinaryPortableGraymap8bitData(
InputStream inputStream) throws IOException
{
DataInputStream dis = new DataInputStream(inputStream);
String line = null;
boolean firstLine = true;
Integer width = null;
Integer maxBrightness = null;
while (true)
{
// The DataInputStream#readLine is deprecated,
// but for ASCII input, it is safe to use it
line = dis.readLine();
if (line == null)
{
break;
}
line = line.trim();
if (line.startsWith("#"))
{
continue;
}
if (firstLine)
{
firstLine = false;
if (!line.equals("P5"))
{
throw new IOException(
"Data is not a binary portable " +
"graymap (P5), but " + line);
}
else
{
continue;
}
}
if (width == null)
{
String tokens[] = line.split(" ");
if (tokens.length < 2)
{
throw new IOException(
"Expected dimensions, found " + line);
}
width = parseInt(tokens[0]);
}
else if (maxBrightness == null)
{
maxBrightness = parseInt(line);
if (maxBrightness > 255)
{
throw new IOException(
"Only 8 bit values supported. " +
"Maximum value is " + maxBrightness);
}
break;
}
}
byte data[] = readFully(inputStream);
return data;
}
public static boolean canRunRootCommands() {
boolean retval = false;
Process suProcess;
try {
suProcess = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
DataInputStream osRes = new DataInputStream(suProcess.getInputStream());
if (null != os && null != osRes) {
// Getting the id of the current user to check if this is root
os.writeBytes("id\n");
os.flush();
String currUid = osRes.readLine();
boolean exitSu = false;
if (null == currUid) {
retval = false;
exitSu = false;
Log.d("ROOT", "Can't get root access or denied by user");
} else if (true == currUid.contains("uid=0")) {
retval = true;
exitSu = true;
Log.d("ROOT", "Root access granted");
} else {
retval = false;
exitSu = true;
Log.d("ROOT", "Root access rejected: " + currUid);
}
if (exitSu) {
os.writeBytes("exit\n");
os.flush();
}
}
} catch (Exception e) {
// Can't get root !
// Probably broken pipe exception on trying to write to output stream (os) after su
// failed, meaning that the device is not rooted
retval = false;
Log.d("ROOT", "Root access rejected [" + e.getClass().getName() + "] : " + e.getMessage());
}
Log.d("ROOT", "Root access granted Has Rooted: " + retval);
return retval;
}
private String prepareSpecification(JobSpecification spec)
throws IllegalSpecException, TaskSubmissionException {
if (spec.getSpecification() != null) {
return spec.getSpecification();
} else {
StringBuffer buf = new StringBuffer("&");
boolean batchJob = spec.isBatchJob();
boolean redirected = spec.isRedirected();
boolean localExecutable = spec.isLocalExecutable();
boolean localInput = spec.isLocalInput();
if (batchJob && redirected) {
throw new IllegalSpecException(
"Cannot redirect the output/error of a batch job");
}
if (redirected) {
this.startGassServer = true;
String gassURL = startGassServer();
appendRSL(buf, "rsl_substitution", "(GLOBUSRUN_GASS_URL "
+ gassURL + ")");
}
// sets the executable
appendRSL(buf, "executable", "/bin/sh");
// sets other parameters
String remote_globus_location = (String) spec
.getAttribute("remote_globus_location");
if (remote_globus_location == null) {
throw new IllegalSpecException(
"Remote Globus location not specified");
}
String rslFile = (String) spec.getAttribute("rsl_file");
if (rslFile == null) {
throw new IllegalSpecException("MPICHG2 RSL file not specified");
}
String mpichg2_rsl = "";
try {
FileInputStream fstream = new FileInputStream(rslFile);
DataInputStream in = new DataInputStream(fstream);
while (in.available() != 0) {
mpichg2_rsl += in.readLine();
}
in.close();
} catch (Exception e) {
throw new IllegalSpecException("Cannot read MPICHG2 rsl from file");
}
String args = "-c \"source " + remote_globus_location
+ "/etc/globus-user-env.sh ; " + remote_globus_location
+ "/bin/globusrun " + mpichg2_rsl + "\"";
appendRSL(buf, "arguments", args);
// if output is to be redirected
if (this.startGassServer && redirected) {
// if no output file is specified, use the stdout
if ((spec.getStdOutput() == null)
|| (spec.getStdOutput().equals(""))) {
appendRSL(buf, "stdout",
"$(GLOBUSRUN_GASS_URL)/dev/stdout-"
+ getTask().getIdentity().toString());
} else {
appendRSL(buf, "stdout", "$(GLOBUSRUN_GASS_URL)/"
+ spec.getStdOutput());
}
} else {
// output on the remote machine
appendRSL(buf, "stdout", spec.getStdOutput());
}
// if error is to be redirected
if (this.startGassServer && redirected) {
// if no error file is specified, use the stdout
if ((spec.getStdError() == null)
|| (spec.getStdError().equals(""))) {
appendRSL(buf, "stderr",
"$(GLOBUSRUN_GASS_URL)/dev/stderr-"
+ getTask().getIdentity().toString());
} else {
appendRSL(buf, "stderr", "$(GLOBUSRUN_GASS_URL)/"
+ spec.getStdError());
}
} else {
// error on the remote machine
appendRSL(buf, "stderr", spec.getStdError());
}
return buf.toString();
}
}
public static boolean canRunRootCommands() {
boolean retval = false;
Process suProcess;
try {
suProcess = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
DataInputStream osRes = new DataInputStream(suProcess.getInputStream());
if (null != os && null != osRes) {
// Getting the id of the current user to check if this is root
os.writeBytes("id\n");
os.flush();
String currUid = osRes.readLine();
boolean exitSu = false;
if (null == currUid) {
retval = false;
exitSu = false;
Log.d("ROOT", "Can't get root access or denied by user");
} else if (true == currUid.contains("uid=0")) {
retval = true;
exitSu = true;
Log.d("ROOT", "Root access granted");
} else {
retval = false;
exitSu = true;
Log.d("ROOT", "Root access rejected: " + currUid);
}
if (exitSu) {
os.writeBytes("exit\n");
os.flush();
}
}
} catch (Exception e) {
// Can't get root !
// Probably broken pipe exception on trying to write to output stream (os) after su
// failed, meaning that the device is not rooted
retval = false;
Log.d("ROOT", "Root access rejected [" + e.getClass().getName() + "] : " + e.getMessage());
}
Log.d("ROOT", "Root access granted Has Rooted: " + retval);
return retval;
}