/// <summary>This assumes each line is one value and creates index by adding values in the order of the lines in the file</summary> /// <param name="file">Which file to load</param> /// <returns>An index built out of the lines in the file</returns> public static IIndex <string> LoadFromFileWithList(string file) { IIndex <string> index = new Edu.Stanford.Nlp.Util.HashIndex <string>(); BufferedReader br = null; try { br = new BufferedReader(new FileReader(file)); for (string line; (line = br.ReadLine()) != null;) { index.Add(line.Trim()); } br.Close(); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } finally { if (br != null) { try { br.Close(); } catch (IOException) { } } } // forget it return(index); }
private string GetSystemProperty(string propName) { string line; BufferedReader input = null; try { var p = Runtime.GetRuntime().Exec("getprop " + propName); input = new BufferedReader(new InputStreamReader(p.InputStream), 1024); line = input.ReadLine(); input.Close(); } catch (IOException ex) { System.Console.WriteLine(ex.Message); return(null); } finally { try { if (input != null) { input.Close(); } } catch (IOException e) { } } return(line); }
/// <summary> /// This is a standard program to read and find a median value based on a file /// of word counts such as: 1 456, 2 132, 3 56... /// </summary> /// <remarks> /// This is a standard program to read and find a median value based on a file /// of word counts such as: 1 456, 2 132, 3 56... Where the first values are /// the word lengths and the following values are the number of times that /// words of that length appear. /// </remarks> /// <param name="path">The path to read the HDFS file from (part-r-00000...00001...etc). /// </param> /// <param name="medianIndex1">The first length value to look for.</param> /// <param name="medianIndex2"> /// The second length value to look for (will be the same as the first /// if there are an even number of words total). /// </param> /// <exception cref="System.IO.IOException">If file cannot be found, we throw an exception. /// </exception> private double ReadAndFindMedian(string path, int medianIndex1, int medianIndex2, Configuration conf) { FileSystem fs = FileSystem.Get(conf); Path file = new Path(path, "part-r-00000"); if (!fs.Exists(file)) { throw new IOException("Output not found!"); } BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(fs.Open(file), Charsets.Utf8)); int num = 0; string line; while ((line = br.ReadLine()) != null) { StringTokenizer st = new StringTokenizer(line); // grab length string currLen = st.NextToken(); // grab count string lengthFreq = st.NextToken(); int prevNum = num; num += System.Convert.ToInt32(lengthFreq); if (medianIndex2 >= prevNum && medianIndex1 <= num) { System.Console.Out.WriteLine("The median is: " + currLen); br.Close(); return(double.ParseDouble(currLen)); } else { if (medianIndex2 >= prevNum && medianIndex1 < num) { string nextCurrLen = st.NextToken(); double theMedian = (System.Convert.ToInt32(currLen) + System.Convert.ToInt32(nextCurrLen )) / 2.0; System.Console.Out.WriteLine("The median is: " + theMedian); br.Close(); return(theMedian); } } } } finally { if (br != null) { br.Close(); } } // error, no median found return(-1); }
public override void Run() { try { InputStreamReader isr = new InputStreamReader(@is); BufferedReader br = new BufferedReader(isr); string s = null; //noinspection ConstantConditions while (s == null && shouldRun) { while ((s = br.ReadLine()) != null) { outputFileHandle.Write(s); outputFileHandle.Write("\n"); } Thread.Sleep(1000); } isr.Close(); br.Close(); outputFileHandle.Flush(); } catch (Exception ex) { System.Console.Out.WriteLine("Problem reading stream :" + @is.GetType().GetCanonicalName() + " " + ex); Sharpen.Runtime.PrintStackTrace(ex); } }
/// <summary>Read job outputs</summary> /// <exception cref="System.IO.IOException"/> internal static IList <TaskResult> ReadJobOutputs(FileSystem fs, Path outdir) { IList <TaskResult> results = new AList <TaskResult>(); foreach (FileStatus status in fs.ListStatus(outdir)) { if (status.GetPath().GetName().StartsWith("part-")) { BufferedReader @in = new BufferedReader(new InputStreamReader(fs.Open(status.GetPath ()), Charsets.Utf8)); try { for (string line; (line = @in.ReadLine()) != null;) { results.AddItem(TaskResult.ValueOf(line)); } } finally { @in.Close(); } } } if (results.IsEmpty()) { throw new IOException("Output not found"); } return(results); }
/// <exception cref="System.IO.IOException"></exception> internal override ICollection <string> GetPackNames() { ICollection <string> packs = new AList <string>(); try { BufferedReader br = this.OpenReader(WalkRemoteObjectDatabase.INFO_PACKS); try { for (; ;) { string s = br.ReadLine(); if (s == null || s.Length == 0) { break; } if (!s.StartsWith("P pack-") || !s.EndsWith(".pack")) { //$NON-NLS-1$ //$NON-NLS-2$ throw this.InvalidAdvertisement(s); } packs.AddItem(Sharpen.Runtime.Substring(s, 2)); } return(packs); } finally { br.Close(); } } catch (FileNotFoundException) { return(packs); } }
public override void SetUp() { base.SetUp(); toLoad = new AList <WindowCacheGetTest.TestObject>(); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream( JGitTestUtil.GetTestResourceFile("all_packed_objects.txt")), Constants.CHARSET)); try { string line; while ((line = br.ReadLine()) != null) { string[] parts = line.Split(" {1,}"); WindowCacheGetTest.TestObject o = new WindowCacheGetTest.TestObject(this); o.id = ObjectId.FromString(parts[0]); o.SetType(parts[1]); // parts[2] is the inflate size // parts[3] is the size-in-pack // parts[4] is the offset in the pack toLoad.AddItem(o); } } finally { br.Close(); } NUnit.Framework.Assert.AreEqual(96, toLoad.Count); }
/// <exception cref="System.IO.IOException"/> public static IList <Edu.Stanford.Nlp.IE.QE.UnitPrefix> LoadPrefixes(string filename) { Pattern commaPattern = Pattern.Compile("\\s*,\\s*"); BufferedReader br = IOUtils.GetBufferedFileReader(filename); string headerString = br.ReadLine(); string[] header = commaPattern.Split(headerString); IDictionary <string, int> headerIndex = new Dictionary <string, int>(); for (int i = 0; i < header.Length; i++) { headerIndex[header[i]] = i; } int iName = headerIndex["name"]; int iPrefix = headerIndex["prefix"]; int iBase = headerIndex["base"]; int iExp = headerIndex["exp"]; int iSystem = headerIndex["system"]; string line; IList <Edu.Stanford.Nlp.IE.QE.UnitPrefix> list = new List <Edu.Stanford.Nlp.IE.QE.UnitPrefix>(); while ((line = br.ReadLine()) != null) { string[] fields = commaPattern.Split(line); double @base = double.ParseDouble(fields[iBase]); double exp = double.ParseDouble(fields[iExp]); double scale = Math.Pow(@base, exp); Edu.Stanford.Nlp.IE.QE.UnitPrefix unitPrefix = new Edu.Stanford.Nlp.IE.QE.UnitPrefix(fields[iName], fields[iPrefix], scale, fields[iSystem]); list.Add(unitPrefix); } br.Close(); return(list); }
private ICollection <string> LoadMWEs() { ICollection <string> mweSet = Generics.NewHashSet(); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(mweFile), "UTF-8")); for (string line; (line = br.ReadLine()) != null;) { mweSet.Add(line.Trim()); } br.Close(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block Sharpen.Runtime.PrintStackTrace(e); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Sharpen.Runtime.PrintStackTrace(e); } catch (IOException e) { // TODO Auto-generated catch block Sharpen.Runtime.PrintStackTrace(e); } return(mweSet); }
private string DownloadData() { HttpURLConnection con = Connector.connect(urlAddress); if (con == null) { return(null); } try { Stream s = new BufferedStream(con.InputStream); BufferedReader br = new BufferedReader(new InputStreamReader(s)); string line; StringBuffer jsonData = new StringBuffer(); while ((line = br.ReadLine()) != null) { jsonData.Append(line); } br.Close(); s.Close(); return(jsonData.ToString()); } catch (Exception e) { Console.WriteLine(e.Message); } return(null); }
/// <summary> /// Read a file with given path and return a string array with it's entire contents. /// </summary> public static string[] ReadAllLines(string path) { if (path == null) { throw new ArgumentNullException("path"); } var file = new JFile(path); if (!file.Exists() || !file.IsFile()) { throw new FileNotFoundException(path); } if (!file.CanRead()) { throw new UnauthorizedAccessException(path); } var reader = new BufferedReader(new FileReader(file)); try { var list = new ArrayList <string>(); string line; while ((line = reader.ReadLine()) != null) { list.Add(line); } return(list.ToArray(new string[list.Count])); } finally { reader.Close(); } }
private async Task <string> RunCommandAsync(string command) { try { var process = Runtime.GetRuntime().Exec(command); using var input = new InputStreamReader(process.InputStream); using var reader = new BufferedReader(input); string line; var output = new System.Text.StringBuilder(); while (!string.IsNullOrEmpty(line = await reader.ReadLineAsync())) { output.AppendLine(line); } reader.Close(); await process.WaitForAsync(); return(output.ToString()); } catch (Java.IO.IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } }
void StartNode() { Trace.WriteLine("Node starting ..."); // Light client nodeProcess = StartProcess($"{nodeBinPath} -d {nodeBasePath} --chain={nodeChainSpecPath} --light --no-prometheus --no-telemetry"); // Full node - Should give the possibility to run either light or full node in the UI //nodeProcess = StartProcess($"{nodeBinPath} -d {nodeBasePath} --chain={nodeChainSpecPath} --no-prometheus --no-telemetry"); _ = Task.Factory.StartNew(async() => { using var input = new InputStreamReader(nodeProcess.ErrorStream); using var reader = new BufferedReader(input); bool ready = false; string line; while (!string.IsNullOrEmpty((line = reader.ReadLine()))) { if (!ready && line.Contains("idle", StringComparison.InvariantCultureIgnoreCase)) { Toast.ShowShortToast("Node is ready."); EventAggregator.GetEvent <NodeStatusEvent>().Publish(NodeStatus.NodeReady); ready = true; } logs.OnNext(line); } reader.Close(); await nodeProcess.WaitForAsync(); }, TaskCreationOptions.LongRunning); }
/// <summary>Copy a delimited text file into a new table in this database.</summary> /// <remarks> /// Copy a delimited text file into a new table in this database. /// <p> /// Equivalent to: /// <code>importReader(new BufferedReader(new FileReader(f)), db, name, delim, "'", filter, false); /// </code> /// </remarks> /// <param name="name">Name of the new table to create</param> /// <param name="f">Source file to import</param> /// <param name="delim">Regular expression representing the delimiter string.</param> /// <param name="quote">the quote character</param> /// <param name="filter">valid import filter</param> /// <param name="useExistingTable"> /// if /// <code>true</code> /// use current table if it already /// exists, otherwise, create new table with unique /// name /// </param> /// <returns>the name of the imported table</returns> /// <seealso cref="ImportReader(System.IO.BufferedReader, Database, string, string, ImportFilter) /// ">ImportReader(System.IO.BufferedReader, Database, string, string, ImportFilter) /// </seealso> /// <exception cref="System.IO.IOException"></exception> public static string ImportFile(FilePath f, Database db, string name, string delim , char quote, ImportFilter filter, bool useExistingTable) { BufferedReader @in = null; try { @in = new BufferedReader(new FileReader(f)); return(ImportReader(@in, db, name, delim, quote, filter, useExistingTable)); } finally { if (@in != null) { try { @in.Close(); } catch (IOException ex) { System.Console.Error.WriteLine("Could not close file " + f.GetAbsolutePath()); Sharpen.Runtime.PrintStackTrace(ex, System.Console.Error); } } } }
// static methods ------------------------------------------------------------- /// <summary> /// Reads from STDIN a sequence of lines, each containing two integers, /// separated by whitespace. /// </summary> /// <remarks> /// Reads from STDIN a sequence of lines, each containing two integers, /// separated by whitespace. Returns a pair of int arrays containing the /// values read. /// </remarks> /// <exception cref="System.Exception"/> private static int[][] ReadInput() { IList <int> rVals = new List <int>(); IList <int> nVals = new List <int>(); BufferedReader @in = new BufferedReader(new InputStreamReader(Runtime.@in)); string line; while ((line = @in.ReadLine()) != null) { string[] tokens = line.Trim().Split("\\s+"); if (tokens.Length != 2) { throw new Exception("Line doesn't contain two tokens: " + line); } int r = int.Parse(tokens[0]); int n = int.Parse(tokens[1]); rVals.Add(r); nVals.Add(n); } @in.Close(); int[][] result = new int[2][]; result[0] = IntegerList2IntArray(rVals); result[1] = IntegerList2IntArray(nVals); return(result); }
/// <summary>Read a standard Git alternates file to discover other object databases.</summary> /// <remarks> /// Read a standard Git alternates file to discover other object databases. /// <p> /// This method is suitable for reading the standard formats of the /// alternates file, such as found in <code>objects/info/alternates</code> /// or <code>objects/info/http-alternates</code> within a Git repository. /// <p> /// Alternates appear one per line, with paths expressed relative to this /// object database. /// </remarks> /// <param name="listPath"> /// location of the alternate file to read, relative to this /// object database (e.g. <code>info/alternates</code>). /// </param> /// <returns> /// the list of discovered alternates. Empty list if the file exists, /// but no entries were discovered. /// </returns> /// <exception cref="System.IO.FileNotFoundException">the requested file does not exist at the given location. /// </exception> /// <exception cref="System.IO.IOException"> /// The connection is unable to read the remote's file, and the /// failure occurred prior to being able to determine if the file /// exists, or after it was determined to exist but before the /// stream could be created. /// </exception> internal virtual ICollection <WalkRemoteObjectDatabase> ReadAlternates(string listPath ) { BufferedReader br = OpenReader(listPath); try { ICollection <WalkRemoteObjectDatabase> alts = new AList <WalkRemoteObjectDatabase>( ); for (; ;) { string line = br.ReadLine(); if (line == null) { break; } if (!line.EndsWith("/")) { line += "/"; } alts.AddItem(OpenAlternate(line)); } return(alts); } finally { br.Close(); } }
private void LoadMWMap(string filename) { mwCounter = new TwoDimensionalCounter <string, string>(); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename)), "UTF-8")); int nLines = 0; for (string line; (line = br.ReadLine()) != null; nLines++) { string[] toks = line.Split("\t"); System.Diagnostics.Debug.Assert(toks.Length == 3); mwCounter.SetCount(toks[0].Trim(), toks[1].Trim(), double.Parse(toks[2].Trim())); } br.Close(); System.Console.Error.Printf("%s: Loaded %d lines from %s into MWE counter%n", this.GetType().FullName, nLines, filename); } catch (UnsupportedEncodingException e) { Sharpen.Runtime.PrintStackTrace(e); } catch (FileNotFoundException e) { Sharpen.Runtime.PrintStackTrace(e); } catch (IOException e) { Sharpen.Runtime.PrintStackTrace(e); } }
/// <exception cref="System.IO.IOException"/> private static void CompareDumpedTreeInFile(FilePath file1, FilePath file2, bool compareQuota, bool print) { if (print) { PrintFile(file1); PrintFile(file2); } BufferedReader reader1 = new BufferedReader(new FileReader(file1)); BufferedReader reader2 = new BufferedReader(new FileReader(file2)); try { string line1 = string.Empty; string line2 = string.Empty; while ((line1 = reader1.ReadLine()) != null && (line2 = reader2.ReadLine()) != null ) { if (print) { System.Console.Out.WriteLine(); System.Console.Out.WriteLine("1) " + line1); System.Console.Out.WriteLine("2) " + line2); } // skip the hashCode part of the object string during the comparison, // also ignore the difference between INodeFile/INodeFileWithSnapshot line1 = line1.ReplaceAll("INodeFileWithSnapshot", "INodeFile"); line2 = line2.ReplaceAll("INodeFileWithSnapshot", "INodeFile"); line1 = line1.ReplaceAll("@[\\dabcdef]+", string.Empty); line2 = line2.ReplaceAll("@[\\dabcdef]+", string.Empty); // skip the replica field of the last block of an // INodeFileUnderConstruction line1 = line1.ReplaceAll("replicas=\\[.*\\]", "replicas=[]"); line2 = line2.ReplaceAll("replicas=\\[.*\\]", "replicas=[]"); if (!compareQuota) { line1 = line1.ReplaceAll("Quota\\[.*\\]", "Quota[]"); line2 = line2.ReplaceAll("Quota\\[.*\\]", "Quota[]"); } // skip the specific fields of BlockInfoUnderConstruction when the node // is an INodeFileSnapshot or an INodeFileUnderConstructionSnapshot if (line1.Contains("(INodeFileSnapshot)") || line1.Contains("(INodeFileUnderConstructionSnapshot)" )) { line1 = line1.ReplaceAll("\\{blockUCState=\\w+, primaryNodeIndex=[-\\d]+, replicas=\\[\\]\\}" , string.Empty); line2 = line2.ReplaceAll("\\{blockUCState=\\w+, primaryNodeIndex=[-\\d]+, replicas=\\[\\]\\}" , string.Empty); } NUnit.Framework.Assert.AreEqual(line1, line2); } NUnit.Framework.Assert.IsNull(reader1.ReadLine()); NUnit.Framework.Assert.IsNull(reader2.ReadLine()); } finally { reader1.Close(); reader2.Close(); } }
public string getDescription() { string description = ""; try { Java.Lang.Process process = Runtime.GetRuntime().Exec("logcat -d HockeyApp:D *:S"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.InputStream)); Java.Lang.StringBuilder log = new Java.Lang.StringBuilder(); string line; while ((line = bufferedReader.ReadLine()) != null) { log.Append(line); log.Append(System.Environment.NewLine); } bufferedReader.Close(); description = log.ToString(); } catch (IOException e) { } return(description); }
/// <param name="file">The file to load the List from</param> /// <param name="c"> /// The Class to instantiate each member of the List. Must have a /// String constructor. /// </param> /// <exception cref="System.Exception"/> public static ICollection <T> LoadCollection <T>(File file, CollectionFactory <T> cf) { System.Type c = typeof(T); Constructor <T> m = c.GetConstructor(new Type[] { typeof(string) }); ICollection <T> result = cf.NewCollection(); BufferedReader @in = new BufferedReader(new FileReader(file)); string line = @in.ReadLine(); while (line != null && line.Length > 0) { try { T o = m.NewInstance(line); result.Add(o); } catch (Exception e) { log.Info("Couldn't build object from line: " + line); Sharpen.Runtime.PrintStackTrace(e); } line = @in.ReadLine(); } @in.Close(); return(result); }
public override void Run() { // keep reading the InputStream until it ends (or an error occurs) try { string line; while ((line = reader.ReadLine()) != null) { Debug.logOutput(string.Format("[{0}] {1}", shell, line)); if (writer != null) { writer.Add(line); } if (listener != null) { listener.OnLine(line); } } } catch (IOException e) { // reader probably closed, expected exit condition } // make sure our stream is closed and resources will be freed try { reader.Close(); } catch (IOException e) { // read already closed } }
// expected /// <exception cref="System.IO.IOException"></exception> private int CountPicks() { int count = 0; FilePath todoFile = new FilePath(db.Directory, "rebase-merge/git-rebase-todo"); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream( todoFile), "UTF-8")); try { string line = br.ReadLine(); while (line != null) { string actionToken = Sharpen.Runtime.Substring(line, 0, line.IndexOf(' ')); RebaseCommand.Action action = null; try { action = RebaseCommand.Action.Parse(actionToken); } catch (Exception) { } // ignore if (action != null) { count++; } line = br.ReadLine(); } return(count); } finally { br.Close(); } }
private static ICollection <string> ReadDict(string filename) { ICollection <string> a = Generics.NewHashSet(); try { /* * if(filename.endsWith("in.as") ||filename.endsWith("in.city") ){ * aDetectorReader = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "Big5_HKSCS")); * }else{ aDetectorReader = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "GB18030")); * } */ BufferedReader aDetectorReader = IOUtils.ReaderFromString(filename, "UTF-8"); //logger.debug("DEBUG: in affDict readDict"); for (string aDetectorLine; (aDetectorLine = aDetectorReader.ReadLine()) != null;) { //logger.debug("DEBUG: affDict: "+filename+" "+aDetectorLine); a.Add(aDetectorLine); } aDetectorReader.Close(); } catch (IOException e) { throw new RuntimeIOException(e); } //logger.info("XM:::readDict(filename: " + filename + ")"); logger.Info("Loading affix dictionary from " + filename + " [done]."); return(a); }
private static IDictionary <string, ICollection <string> > ReadDict(string filename) { IDictionary <string, ICollection <string> > char_dict; try { BufferedReader detectorReader = IOUtils.ReaderFromString(filename, "UTF-8"); char_dict = Generics.NewHashMap(); //logger.debug("DEBUG: in CorpusChar readDict"); for (string detectorLine; (detectorLine = detectorReader.ReadLine()) != null;) { string[] fields = detectorLine.Split(" "); string tag = fields[0]; ICollection <string> chars = char_dict[tag]; if (chars == null) { chars = Generics.NewHashSet(); char_dict[tag] = chars; } //logger.debug("DEBUG: CorpusChar: "+filename+" "+fields[1]); chars.Add(fields[1]); } detectorReader.Close(); } catch (IOException e) { throw new RuntimeIOException(e); } logger.Info("Loading character dictionary file from " + filename + " [done]."); return(char_dict); }
/// <summary> /// Tally up the values and ensure that we got as much data /// out as we put in. /// </summary> /// <remarks> /// Tally up the values and ensure that we got as much data /// out as we put in. /// Each mapper generated 'NUMBER_FILE_VAL' values (0..NUMBER_FILE_VAL-1). /// Verify that across all our reducers we got exactly this much /// data back. /// </remarks> /// <exception cref="System.Exception"/> private void VerifyNumberJob(int numMaps) { Path outputDir = GetOutputPath(); Configuration conf = new Configuration(); FileSystem fs = FileSystem.GetLocal(conf); FileStatus[] stats = fs.ListStatus(outputDir); int valueSum = 0; foreach (FileStatus f in stats) { FSDataInputStream istream = fs.Open(f.GetPath()); BufferedReader r = new BufferedReader(new InputStreamReader(istream)); string line = null; while ((line = r.ReadLine()) != null) { valueSum += Sharpen.Extensions.ValueOf(line.Trim()); } r.Close(); } int maxVal = NumberFileVal - 1; int expectedPerMapper = maxVal * (maxVal + 1) / 2; int expectedSum = expectedPerMapper * numMaps; Log.Info("expected sum: " + expectedSum + ", got " + valueSum); NUnit.Framework.Assert.AreEqual("Didn't get all our results back", expectedSum, valueSum ); }
/// <summary> /// Loads all proximity classes from the hard disk The WORDS map must be /// created before! /// </summary> /// <exception cref="System.IO.IOException"/> public static void LoadProximityClasses(string proxFileName) { log.Info("Loading proximity classes..."); BufferedReader @in = null; try { @in = new BufferedReader(new FileReader(proxFileName)); } catch (IOException) { log.Info("Warning: no proximity database found."); return; } string line; while ((line = @in.ReadLine()) != null) { List <string> tokens = SimpleTokenize.Tokenize(line); if (tokens.Count > 0) { int key = Words.Get(tokens[0]); List <int> value = new List <int>(); for (int i = 0; i < tokens.Count && i < ProximityClassSize; i++) { int word = Words.Get(tokens[i]); value.Add(word); } ProxClasses[key] = value; } } @in.Close(); log.Info("Finished loading proximity classes."); }
/// <summary>Send the 4letterword</summary> /// <param name="host">the destination host</param> /// <param name="port">the destination port</param> /// <param name="cmd">the 4letterword</param> /// <returns/> /// <exception cref="System.IO.IOException"/> public static string Send4LetterWord(string host, int port, string cmd) { Log.Info("connecting to " + host + " " + port); Socket sock = Extensions.CreateSocket(host, port); BufferedReader reader = null; try { OutputStream outstream = sock.GetOutputStream(); outstream.Write(Runtime.GetBytesForString(cmd)); outstream.Flush(); // this replicates NC - close the output stream before reading sock.ShutdownOutput(); reader = new BufferedReader(new InputStreamReader(sock.GetInputStream())); StringBuilder sb = new StringBuilder(); string line; while ((line = reader.ReadLine()) != null) { sb.Append(line + "\n"); } return(sb.ToString()); } finally { sock.Close(); if (reader != null) { reader.Close(); } } }
/// <summary>access a url, ignoring some IOException such as the page does not exist</summary> /// <exception cref="System.IO.IOException"/> internal static void Access(string urlstring) { Log.Warn("access " + urlstring); Uri url = new Uri(urlstring); URLConnection connection = url.OpenConnection(); connection.Connect(); try { BufferedReader @in = new BufferedReader(new InputStreamReader(connection.GetInputStream ())); try { for (; @in.ReadLine() != null;) { } } finally { @in.Close(); } } catch (IOException ioe) { Log.Warn("urlstring=" + urlstring, ioe); } }
public static void Print(string bt_printer, string value) { try{ if (bt_printer != "" || bt_printer != null || bt_printer.Length > 0) { var x = BluetoothAdapter.DefaultAdapter.BondedDevices; BluetoothSocket socket = null; BufferedReader inReader = null; BufferedWriter outReader = null; BluetoothDevice hxm = BluetoothAdapter.DefaultAdapter.GetRemoteDevice(bt_printer); UUID applicationUUID = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"); socket = hxm.CreateRfcommSocketToServiceRecord(applicationUUID); socket.Connect(); inReader = new BufferedReader(new InputStreamReader(socket.InputStream)); outReader = new BufferedWriter(new OutputStreamWriter(socket.OutputStream)); outReader.Write(value); outReader.Flush(); Thread.Sleep(5 * 1000); var s = inReader.Ready(); inReader.Skip(0); //close all inReader.Close(); socket.Close(); outReader.Close(); } }catch (Exception ex) { Shared.Services.Logs.Insights.Send("Print", ex); } }
/// <summary>For debugging</summary> /// <param name="args"/> public static void Main(string[] args) { if (args.Length != 1) { System.Console.Error.Printf("Usage: java %s file%n", typeof(FrenchMorphoFeatureSpecification).FullName); System.Environment.Exit(-1); } try { BufferedReader br = new BufferedReader(new FileReader(args[0])); MorphoFeatureSpecification mfs = new FrenchMorphoFeatureSpecification(); //Activate all features for debugging mfs.Activate(MorphoFeatureSpecification.MorphoFeatureType.Gen); mfs.Activate(MorphoFeatureSpecification.MorphoFeatureType.Num); mfs.Activate(MorphoFeatureSpecification.MorphoFeatureType.Per); for (string line; (line = br.ReadLine()) != null;) { MorphoFeatures feats = mfs.StrToFeatures(line); System.Console.Out.Printf("%s\t%s%n", line.Trim(), feats.ToString()); } br.Close(); } catch (FileNotFoundException e) { Sharpen.Runtime.PrintStackTrace(e); } catch (IOException e) { Sharpen.Runtime.PrintStackTrace(e); } }
private const int ICON_SIZE = 32; // dip protected override void OnCreate(Bundle b) { base.OnCreate(b); SetContentView(R.Layouts.sharing_receiver_support); float density = GetResources().GetDisplayMetrics().Density; int iconSize = (int) (ICON_SIZE * density + 0.5f); ShareCompat.IntentReader intentReader = ShareCompat.IntentReader.From(this); // The following provides attribution for the app that shared the data with us. TextView info = (TextView) FindViewById(R.Ids.app_info); Drawable d = intentReader.GetCallingActivityIcon(); d.SetBounds(0, 0, iconSize, iconSize); info.SetCompoundDrawables(d, null, null, null); info.SetText(intentReader.GetCallingApplicationLabel()); TextView tv = (TextView) FindViewById(R.Ids.text); StringBuilder txt = new StringBuilder("Received share!\nText was: "); txt.Append(intentReader.GetText()); txt.Append("\n"); txt.Append("Streams included:\n"); int N = intentReader.GetStreamCount(); for (int i = 0; i < N; i++) { Uri uri = intentReader.GetStream(i); txt.Append("Share included stream " + i + ": " + uri + "\n"); try { BufferedReader reader = new BufferedReader(new InputStreamReader( GetContentResolver().OpenInputStream(uri))); try { txt.Append(reader.ReadLine() + "\n"); } catch (IOException e) { Log.E(TAG, "Reading stream threw exception", e); } finally { reader.Close(); } } catch (FileNotFoundException e) { Log.E(TAG, "File not found from share.", e); } catch (IOException e) { Log.D(TAG, "I/O Error", e); } } tv.SetText(txt.ToString()); }
/// <summary> /// Read a file with given path and return a string array with it's entire contents. /// </summary> public static string[] ReadAllLines(string path) { if (path == null) throw new ArgumentNullException("path"); var file = new JFile(path); if (!file.Exists() || !file.IsFile()) throw new FileNotFoundException(path); if (!file.CanRead()) throw new UnauthorizedAccessException(path); var reader = new BufferedReader(new FileReader(file)); try { var list = new ArrayList<string>(); string line; while ((line = reader.ReadLine()) != null) { list.Add(line); } return list.ToArray(new string[list.Count]); } finally { reader.Close(); } }
public static string[] readFile(string path) { BufferedReader input = new BufferedReader(new FileReader(path)); string line = null; List<string> _list = new List<string>(); while ((line = input.ReadLine()) != null) { line = line.Replace("@%@", ","); _list.Add(line); } input.Close(); return _list.ToArray(); }