Exemplo n.º 1
0
        /// <summary>
        /// Outputs the device name and ip.
        /// </summary>
        /// <param name="outputSocket">Output socket.</param>
        /// <param name="deviceName">Device name.</param>
        /// <param name="deviceAddress">Device address.</param>
        //端末名とIPアドレスのセットを送る
        void outputDeviceNameAndIp(Socket outputSocket, String deviceName, String deviceAddress)//*** Host And Guest ***
        {
            BufferedWriter bufferedWriter;

            try
            {
                bufferedWriter = new BufferedWriter(
                    new OutputStreamWriter(outputSocket.OutputStream)
                    );
                //デバイス名を書き込む
                bufferedWriter.Write(deviceName);
                bufferedWriter.NewLine();
                //IPアドレスを書き込む
                bufferedWriter.Write(deviceAddress);
                bufferedWriter.NewLine();
                //出力終了の文字列を書き込む
                bufferedWriter.Write("outputFinish");
                //出力する
                bufferedWriter.Flush();
            }
            catch (IOException e)
            {
                e.PrintStackTrace();
            }
        }
Exemplo n.º 2
0
        public void WriteSensorLog(IEnumerable <string> commands)
        {
            try
            {
                if (IsLogEnable)
                {
                    File file = new File(Android.OS.Environment.ExternalStorageDirectory, SensorFileName + ".txt");
                    //第二个参数意义是说是否以append方式添加内容
                    BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
                    //记录日志时间 //记录时间
                    string info = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "-";

                    //我需要记录我接收到这条数据的时间
                    for (int i = 0; i < commands.Count(); i++)
                    {
                        if (i == 0)
                        {
                            bw.Write(info + commands.ElementAt(i));
                        }
                        else
                        {
                            bw.Write(commands.ElementAt(i));
                        }

                        bw.Write("\r\n");
                    }
                    bw.Flush();
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Run a very simple server.
        /// </summary>
        private void RunServer()
        {
            try
            {
                Log.I("SimpleHttpServer", "Creating server socket");
                var serverSocket = new ServerSocket(PORT);
                var requestCount = 0;
                try
                {
                    while (!stop)
                    {
                        Log.I("SimpleHttpServer", "Waiting for connection");
                        var socket = serverSocket.Accept();

                        var input  = new BufferedReader(new InputStreamReader(socket.GetInputStream()));
                        var output = new BufferedWriter(new OutputStreamWriter(socket.GetOutputStream()));

                        string line;
                        Log.I("SimpleHttpServer", "Reading request");
                        while ((line = input.ReadLine()) != null)
                        {
                            Log.I("SimpleHttpServer", "Received: " + line);
                            if (line.Length == 0)
                            {
                                break;
                            }
                        }

                        Log.I("SimpleHttpServer", "Sending response");
                        output.Write("HTTP/1.1 200 OK\r\n");
                        output.Write("\r\n");
                        output.Write(string.Format("Hello world {0}\r\n", requestCount));
                        output.Flush();

                        socket.Close();
                        requestCount++;
                    }
                }
                finally
                {
                    serverSocket.Close();
                }
            }
            catch (Exception ex)
            {
                Log.E("SimpleHttpServer", "Connection error", ex);
            }
        }
Exemplo n.º 4
0
 private void printLine(string pStrTextoImprimir)
 {
     byte[] bytes = null;
     bytes = new byte[pStrTextoImprimir.Length * sizeof(char)];
     System.Buffer.BlockCopy(pStrTextoImprimir.ToCharArray(), 0, bytes, 0, bytes.Length);
     outReader.Write(pStrTextoImprimir + "\n");
 }
Exemplo n.º 5
0
        public void put(string key, string value)
        {
            File           file   = mCache.newFile(key);
            BufferedWriter writer = null;

            try
            {
                writer = new BufferedWriter(new FileWriter(file), 1024);
                writer.Write(value);
            }
            catch (IOException ex)
            {
                ex.PrintStackTrace();
            }
            finally
            {
                if (writer != null)
                {
                    try
                    {
                        writer.Flush();
                        writer.Dispose();
                    }
                    catch (IOException ex)
                    {
                        ex.PrintStackTrace();
                    }
                }

                mCache.put(file);
            }
        }
Exemplo n.º 6
0
        public void SaveCurrentData(Context context)
        {
            try
            {
                var file = new File(context.FilesDir, Constants.MedicationFile);
                var data = new JSONArray();

                if (DiseaseList.Count == 0)
                {
                    file.Delete();
                    file = new File(context.FilesDir, Constants.MedicationFile);
                }

                for (var i = 0; i < DiseaseList.Count; i++)
                {
                    data.Put(CreateJsonObject(DiseaseList[i]));
                }

                var fileWriter        = new FileWriter(file);
                var outBufferedWriter = new BufferedWriter(fileWriter);
                outBufferedWriter.Write(data.ToString());
                outBufferedWriter.Close();
            }
            catch (IOException e)
            {
                e.PrintStackTrace();
            }
        }
Exemplo n.º 7
0
 /**
  * Writes a message to the log file on the device.
  * @param logMessageTag A tag identifying a group of log messages.
  * @param logMessage The message to add to the log.
  */
 private static void logToFile(Context context, string logMessageTag, string logMessage)
 {
     try
     {
         // Gets the log file from the root of the primary storage. If it does
         // not exist, the file is created.
         File logFile = new File(System.Environment.CurrentDirectory, "TestApplicationLog.txt");
         if (!logFile.Exists())
         {
             logFile.CreateNewFile();
         }
         // Write the message to the log with a timestamp
         BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, true));
         writer.Write(string.Format("%1s [%2s]:%3s\r\n",
                                    getDateTimeStamp(), logMessageTag, logMessage));
         writer.Close();
         // Refresh the data so it can seen when the device is plugged in a
         // computer. You may have to unplug and replug to see the latest
         // changes
         MediaScannerConnection.ScanFile(context,
                                         new string[] { logFile.ToString() },
                                         null,
                                         null);
     }
     catch (IOException)
     {
         Log.Error("com.cindypotvin.Logger", "Unable to log exception to file.");
     }
 }
Exemplo n.º 8
0
        private void BtnMapExport_Click(object sender, EventArgs e)
        {
            try
            {
                //string Map = dataService.GetAllMapLines().ToJson();
                var maps = dataService.GetAllMapLines();

                if (!System.IO.Directory.Exists(DictoryPath + "/" + "map"))
                {
                    System.IO.Directory.CreateDirectory(DictoryPath + "/" + "map");
                }
                else
                {
                    System.IO.DirectoryInfo theFolder = new System.IO.DirectoryInfo(DictoryPath + "/" + "map");
                    foreach (var item in theFolder.GetFiles())
                    {
                        //每次导出我会清空整个文件夹
                        System.IO.File.Delete(item.FullName);
                    }
                }
                foreach (var item in maps)
                {
                    File           file = new File(DictoryPath + "/" + "map", item.Name + ".map");
                    BufferedWriter bw   = new BufferedWriter(new FileWriter(file, false));
                    bw.Write(item.ToJson());
                    bw.Flush();
                }
                textViewTips.Text = "地图导出成功";
            }
            catch (Exception ex)
            {
                textViewTips.Text = "地图导出失败" + ex.Message;
            }
        }
Exemplo n.º 9
0
        public virtual void TestReadLines()
        {
            File file = new File(this.dir, "lines.txt");
            IEnumerable <string> iterable;

            Write("abc", file);
            iterable = IOUtils.ReadLines(file);
            NUnit.Framework.Assert.AreEqual("abc", StringUtils.Join(iterable, "!"));
            NUnit.Framework.Assert.AreEqual("abc", StringUtils.Join(iterable, "!"));
            Write("abc\ndef\n", file);
            iterable = IOUtils.ReadLines(file);
            NUnit.Framework.Assert.AreEqual("abc!def", StringUtils.Join(iterable, "!"));
            NUnit.Framework.Assert.AreEqual("abc!def", StringUtils.Join(iterable, "!"));
            Write("\na\nb\n", file);
            iterable = IOUtils.ReadLines(file.GetPath());
            NUnit.Framework.Assert.AreEqual("!a!b", StringUtils.Join(iterable, "!"));
            NUnit.Framework.Assert.AreEqual("!a!b", StringUtils.Join(iterable, "!"));
            Write(string.Empty, file);
            iterable = IOUtils.ReadLines(file);
            NUnit.Framework.Assert.IsFalse(iterable.GetEnumerator().MoveNext());
            Write("\n", file);
            iterable = IOUtils.ReadLines(file.GetPath());
            IEnumerator <string> iterator = iterable.GetEnumerator();

            NUnit.Framework.Assert.IsTrue(iterator.MoveNext());
            iterator.Current;
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(file))));

            writer.Write("\nzipped\ntext\n");
            writer.Close();
            iterable = IOUtils.ReadLines(file, typeof(GZIPInputStream));
            NUnit.Framework.Assert.AreEqual("!zipped!text", StringUtils.Join(iterable, "!"));
            NUnit.Framework.Assert.AreEqual("!zipped!text", StringUtils.Join(iterable, "!"));
        }
Exemplo n.º 10
0
 private void BtnExport_Click(object sender, EventArgs e)
 {
     // throw new NotImplementedException();
     try
     {
         textViewTips.Text = "正在进行配置导出,请等待";
         JSONStringer   js             = new JSONStringer();
         var            dataService    = Singleton.GetDataService;
         string         Setting        = dataService.AllSettings.ToJson();
         string         LightExamGroup = dataService.AllLightExamItems.ToJson();
         string         Map            = dataService.GetAllMapLines().ToJson();
         string         config         = Setting + "@" + LightExamGroup + "@" + Map;
         File           file           = new File(DictoryPath, "config.config");
         BufferedWriter bw             = new BufferedWriter(new FileWriter(file, false));
         bw.Write(config);
         bw.Flush();
         textViewTips.Text = "配置导出成功";
     }
     catch (Exception ex)
     {
         textViewTips.Text = "一键导出失败";
         Logger.Error("一键导出", ex.Message);
     }
     //串口服务器//自己买一个呗//好简单的东西哟
     //一键导出把配置,灯光分组,以及地图都导出
 }
Exemplo n.º 11
0
        /// <exception cref="System.IO.IOException"/>
        public virtual void TestGzipCodecWrite(bool useNative)
        {
            // Create a gzipped file using a compressor from the CodecPool,
            // and try to read it back via the regular GZIPInputStream.
            // Use native libs per the parameter
            Configuration conf = new Configuration();

            conf.SetBoolean(CommonConfigurationKeys.IoNativeLibAvailableKey, useNative);
            if (useNative)
            {
                if (!ZlibFactory.IsNativeZlibLoaded(conf))
                {
                    Log.Warn("testGzipCodecWrite skipped: native libs not loaded");
                    return;
                }
            }
            else
            {
                NUnit.Framework.Assert.IsFalse("ZlibFactory is using native libs against request"
                                               , ZlibFactory.IsNativeZlibLoaded(conf));
            }
            // Ensure that the CodecPool has a BuiltInZlibDeflater in it.
            Compressor zlibCompressor = ZlibFactory.GetZlibCompressor(conf);

            NUnit.Framework.Assert.IsNotNull("zlibCompressor is null!", zlibCompressor);
            Assert.True("ZlibFactory returned unexpected deflator", useNative
                                 ? zlibCompressor is ZlibCompressor : zlibCompressor is BuiltInZlibDeflater);
            CodecPool.ReturnCompressor(zlibCompressor);
            // Create a GZIP text file via the Compressor interface.
            CompressionCodecFactory ccf   = new CompressionCodecFactory(conf);
            CompressionCodec        codec = ccf.GetCodec(new Path("foo.gz"));

            Assert.True("Codec for .gz file is not GzipCodec", codec is GzipCodec
                        );
            string msg      = "This is the message we are going to compress.";
            string tmpDir   = Runtime.GetProperty("test.build.data", "/tmp/");
            string fileName = new Path(new Path(tmpDir), "testGzipCodecWrite.txt.gz").ToString
                                  ();
            BufferedWriter w = null;
            Compressor     gzipCompressor = CodecPool.GetCompressor(codec);

            if (null != gzipCompressor)
            {
                // If it gives us back a Compressor, we should be able to use this
                // to write files we can then read back with Java's gzip tools.
                OutputStream os = new CompressorStream(new FileOutputStream(fileName), gzipCompressor
                                                       );
                w = new BufferedWriter(new OutputStreamWriter(os));
                w.Write(msg);
                w.Close();
                CodecPool.ReturnCompressor(gzipCompressor);
                VerifyGzipFile(fileName, msg);
            }
            // Create a gzip text file via codec.getOutputStream().
            w = new BufferedWriter(new OutputStreamWriter(codec.CreateOutputStream(new FileOutputStream
                                                                                       (fileName))));
            w.Write(msg);
            w.Close();
            VerifyGzipFile(fileName, msg);
        }
Exemplo n.º 12
0
        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);
            }
        }
Exemplo n.º 13
0
        public virtual void SaveToFilename(string file)
        {
            BufferedWriter bw = null;

            try
            {
                bw = new BufferedWriter(new FileWriter(file));
                for (int i = 0; i < sz; i++)
                {
                    bw.Write(i + "=" + Get(i) + '\n');
                }
                bw.Close();
            }
            catch (IOException e)
            {
                Sharpen.Runtime.PrintStackTrace(e);
            }
            finally
            {
                if (bw != null)
                {
                    try
                    {
                        bw.Close();
                    }
                    catch (IOException)
                    {
                    }
                }
            }
        }
Exemplo n.º 14
0
        /**
         * 打开日志文件并写入日志
         *
         * @return
         **/
        private /*synchronized*/ static void log2File(string mylogtype, string tag, string text)
        {
            Date   nowtime        = new Date();
            string date           = FILE_SUFFIX.Format(nowtime);
            string dateLogContent = LOG_FORMAT.Format(nowtime) + ":" + mylogtype + ":" + tag + ":" + text; // 日志输出格式
            File   destDir        = new File(LOG_FILE_PATH);

            if (!destDir.Exists())
            {
                destDir.Mkdirs();
            }
            File file = new File(LOG_FILE_PATH, LOG_FILE_NAME + date);

            try
            {
                FileWriter     filerWriter = new FileWriter(file, true);
                BufferedWriter bufWriter   = new BufferedWriter(filerWriter);
                bufWriter.Write(dateLogContent);
                bufWriter.NewLine();
                bufWriter.Close();
                filerWriter.Close();
            }
            catch (IOException e)
            {
                e.PrintStackTrace();
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Run a very simple server.
        /// </summary>
        private void RunServer()
        {
            try
            {
                Log.I("SimpleHttpServer", "Creating server socket");
                var serverSocket = new ServerSocket(PORT);
                var requestCount = 0;
                try
                {
                    while (!stop)
                    {
                        Log.I("SimpleHttpServer", "Waiting for connection");
                        var socket = serverSocket.Accept();

                        var input = new BufferedReader(new InputStreamReader(socket.GetInputStream()));
                        var output = new BufferedWriter(new OutputStreamWriter(socket.GetOutputStream()));

                        string line;
                        Log.I("SimpleHttpServer", "Reading request");
                        while ((line = input.ReadLine()) != null)
                        {
                            Log.I("SimpleHttpServer", "Received: " + line);
                            if (line.Length == 0)
                                break;
                        }

                        Log.I("SimpleHttpServer", "Sending response");
                        output.Write("HTTP/1.1 200 OK\r\n");
                        output.Write("\r\n");
                        output.Write(string.Format("Hello world {0}\r\n", requestCount));
                        output.Flush();

                        socket.Close();
                        requestCount++;
                    }
                }
                finally
                {
                    serverSocket.Close();
                }
            }
            catch (Exception ex)
            {
                Log.E("SimpleHttpServer", "Connection error", ex);
            }
        }
Exemplo n.º 16
0
 private void WriteTextFile(File file, string text)
 {
     using (BufferedWriter writer = new BufferedWriter(new FileWriter(file)))
     {
         writer.Write(text);
         writer.Flush();
     }
 }
Exemplo n.º 17
0
        public void UncaughtException(Thread thread, Throwable ex)
        {
            File file = new File(Android.OS.Environment.ExternalStorageDirectory, "SpecialError.txt");
            //第二个参数意义是说是否以append方式添加内容
            BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
            //记录日志时间
            string info = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + "---" + ex.Message;

            //自动换行
            bw.Write(info);
            bw.Write("\r\n");//
            bw.Flush();

            // showToast(mContext, "很抱歉,程序遭遇异常,即将退出!");
            Toast.MakeText(mContext, "很抱歉,程序遭遇异常,即将退出!", ToastLength.Long);
            Thread.Sleep(2000);
        }
 /// <exception cref="System.IO.IOException"/>
 public static void OutputMatrix(BufferedWriter bout, SimpleMatrix matrix)
 {
     for (int i = 0; i < matrix.GetNumElements(); ++i)
     {
         bout.Write("  " + matrix.Get(i));
     }
     bout.NewLine();
 }
Exemplo n.º 19
0
 /// <exception cref="System.IO.IOException"/>
 public static void CommunicateWithNERServer(string host, int port, string charset, BufferedReader input, BufferedWriter output, bool closeOnBlank)
 {
     if (host == null)
     {
         host = "localhost";
     }
     for (string userInput; (userInput = input.ReadLine()) != null;)
     {
         if (userInput.Matches("\\n?"))
         {
             if (closeOnBlank)
             {
                 break;
             }
             else
             {
                 continue;
             }
         }
         try
         {
             // TODO: why not keep the same socket for multiple lines?
             Socket         socket = new Socket(host, port);
             PrintWriter    @out   = new PrintWriter(new OutputStreamWriter(socket.GetOutputStream(), charset), true);
             BufferedReader @in    = new BufferedReader(new InputStreamReader(socket.GetInputStream(), charset));
             // send material to NER to socket
             @out.Println(userInput);
             // Print the results of NER
             string result;
             while ((result = @in.ReadLine()) != null)
             {
                 if (output == null)
                 {
                     EncodingPrintWriter.Out.Println(result, charset);
                 }
                 else
                 {
                     output.Write(result);
                     output.NewLine();
                 }
             }
             @in.Close();
             socket.Close();
         }
         catch (UnknownHostException)
         {
             log.Info("Cannot find host: ");
             log.Info(host);
             return;
         }
         catch (IOException)
         {
             log.Info("I/O error in the connection to: ");
             log.Info(host);
             return;
         }
     }
 }
 public virtual void SetUp()
 {
     lock (typeof(RegexNERSequenceClassifierTest))
     {
         if (tempFile == null)
         {
             tempFile = File.CreateTempFile("regexnertest.patterns", "txt");
             FileWriter     fout = new FileWriter(tempFile);
             BufferedWriter bout = new BufferedWriter(fout);
             bout.Write("sausage\tfood\n");
             bout.Write("(avocet|curlew)(s?)\tshorebird\n");
             bout.Write("shoreline park\tpark\n");
             bout.Flush();
             fout.Close();
         }
     }
     sentences    = new List <IList <CoreLabel> >();
     NERsentences = new List <IList <CoreLabel> >();
     NUnit.Framework.Assert.AreEqual(words.Length, tags.Length);
     NUnit.Framework.Assert.AreEqual(words.Length, ner.Length);
     for (int snum = 0; snum < words.Length; ++snum)
     {
         string[] wordPieces = words[snum].Split(" ");
         string[] tagPieces  = tags[snum].Split(" ");
         string[] nerPieces  = ner[snum].Split(" ");
         NUnit.Framework.Assert.AreEqual(wordPieces.Length, tagPieces.Length);
         NUnit.Framework.Assert.AreEqual(wordPieces.Length, nerPieces.Length, "Input " + snum + " " + words[snum] + " of different length than " + ner[snum]);
         IList <CoreLabel> sentence    = new List <CoreLabel>();
         IList <CoreLabel> NERsentence = new List <CoreLabel>();
         for (int wnum = 0; wnum < wordPieces.Length; ++wnum)
         {
             CoreLabel token = new CoreLabel();
             token.SetWord(wordPieces[wnum]);
             token.SetTag(tagPieces[wnum]);
             sentence.Add(token);
             CoreLabel NERtoken = new CoreLabel();
             NERtoken.SetWord(wordPieces[wnum]);
             NERtoken.SetTag(tagPieces[wnum]);
             NERtoken.SetNER(nerPieces[wnum]);
             NERsentence.Add(NERtoken);
         }
         sentences.Add(sentence);
         NERsentences.Add(NERsentence);
     }
 }
 public static void WriteTrees(IList <Tree> trees, string outputFile)
 {
     logger.Info("Writing new trees to " + outputFile);
     try
     {
         BufferedWriter @out = new BufferedWriter(new FileWriter(outputFile));
         foreach (Tree tree in trees)
         {
             @out.Write(tree.ToString());
             @out.Write("\n");
         }
         @out.Close();
     }
     catch (IOException e)
     {
         throw new RuntimeIOException(e);
     }
 }
Exemplo n.º 22
0
        /// <exception cref="System.Exception"/>
        public static void Print(string[][] cols)
        {
            BufferedWriter @out = new BufferedWriter(new FileWriter(outputFilename));

            foreach (string[] col in cols)
            {
                if (col.Length >= 2)
                {
                    @out.Write(col[0] + "\t" + col[1] + "\n");
                }
                else
                {
                    @out.Write("\n");
                }
            }
            @out.Flush();
            @out.Close();
        }
Exemplo n.º 23
0
            public override void Run()
            {
                int failures = 0;

                try
                {
                    FileOutputStream   fos = new FileOutputStream(this.filename);
                    OutputStreamWriter ow  = new OutputStreamWriter(fos, "utf-8");
                    BufferedWriter     bw  = new BufferedWriter(ow);
                    foreach (IList <IHasWord> sentence in this.sentences)
                    {
                        Tree tree = this._enclosing.parser.ParseTree(sentence);
                        if (tree == null)
                        {
                            ++failures;
                            ParserPanel.log.Info("Failed on sentence " + sentence);
                        }
                        else
                        {
                            bw.Write(tree.ToString());
                            bw.NewLine();
                        }
                        this.progress.SetValue(this.progress.GetValue() + 1);
                        if (this.cancelled)
                        {
                            break;
                        }
                    }
                    bw.Flush();
                    bw.Close();
                    ow.Close();
                    fos.Close();
                }
                catch (IOException e)
                {
                    JOptionPane.ShowMessageDialog(this._enclosing, "Could not save file " + this.filename + "\n" + e, null, JOptionPane.ErrorMessage);
                    Sharpen.Runtime.PrintStackTrace(e);
                    this._enclosing.SetStatus("Error saving parsed document");
                }
                if (failures == 0)
                {
                    this.button.SetText("Success!");
                }
                else
                {
                    this.button.SetText("Done.  " + failures + " parses failed");
                }
                if (this.cancelled && failures == 0)
                {
                    this.dialog.SetVisible(false);
                }
                else
                {
                    this.button.AddActionListener(null);
                }
            }
Exemplo n.º 24
0
        /// <summary>write cofiguration</summary>
        /// <returns/>
        /// <exception cref="System.IO.IOException"/>
        private FilePath WriteFile()
        {
            FilePath       f          = new FilePath(testDir, "tst.xml");
            BufferedWriter @out       = new BufferedWriter(new FileWriter(f));
            string         properties = "<properties><property key=\"key\" value=\"value\"/><property key=\"key1\" value=\"value1\"/></properties>";

            @out.Write("<queues>");
            @out.NewLine();
            @out.Write("<queue><name>first</name><acl-submit-job>user1,user2 group1,group2</acl-submit-job><acl-administer-jobs>user3,user4 group3,group4</acl-administer-jobs><state>running</state></queue>"
                       );
            @out.NewLine();
            @out.Write("<queue><name>second</name><acl-submit-job>u1,u2 g1,g2</acl-submit-job>"
                       + properties + "<state>stopped</state></queue>");
            @out.NewLine();
            @out.Write("</queues>");
            @out.Flush();
            @out.Close();
            return(f);
        }
 private static void WriteTrees(string filename, IList <Tree> trees, IList <int> treeIds)
 {
     try
     {
         FileOutputStream fos  = new FileOutputStream(filename);
         BufferedWriter   bout = new BufferedWriter(new OutputStreamWriter(fos));
         foreach (int id in treeIds)
         {
             bout.Write(trees[id].ToString());
             bout.Write("\n");
         }
         bout.Flush();
         fos.Close();
     }
     catch (IOException e)
     {
         throw new RuntimeIOException(e);
     }
 }
Exemplo n.º 26
0
 public void WriteFile(string Msg, string FileName)
 {
     try
     {
         File file = new File(Android.OS.Environment.ExternalStorageDirectory + "/" + this.FolderName, FileName + ".txt");
         //第二个参数意义是说是否以append方式添加内容
         BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
         //记录日志时间
         string info = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + "---" + Msg;
         //自动换行
         bw.Write(info);
         bw.Write("\r\n");//
         bw.Flush();
     }
     catch (Exception ex)
     {
         Error("WriteLog" + ex.Message);
     }
 }
Exemplo n.º 27
0
 public static void WriteSystemLog(string Msg)
 {
     try
     {
         File file = new File(Android.OS.Environment.ExternalStorageDirectory, "SystemLog" + ".txt");
         //第二个参数意义是说是否以append方式添加内容
         BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
         //记录日志时间
         string info = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + "---" + Msg;
         //自动换行
         bw.Write(info);
         bw.Write("\r\n");//
         bw.Flush();
     }
     catch (Exception ex)
     {
         return;
     }
 }
Exemplo n.º 28
0
        public virtual void TestGzipLongOverflow()
        {
            Log.Info("testGzipLongOverflow");
            // Don't use native libs for this test.
            Configuration conf = new Configuration();

            conf.SetBoolean(CommonConfigurationKeys.IoNativeLibAvailableKey, false);
            NUnit.Framework.Assert.IsFalse("ZlibFactory is using native libs against request"
                                           , ZlibFactory.IsNativeZlibLoaded(conf));
            // Ensure that the CodecPool has a BuiltInZlibInflater in it.
            Decompressor zlibDecompressor = ZlibFactory.GetZlibDecompressor(conf);

            NUnit.Framework.Assert.IsNotNull("zlibDecompressor is null!", zlibDecompressor);
            Assert.True("ZlibFactory returned unexpected inflator", zlibDecompressor
                        is BuiltInZlibInflater);
            CodecPool.ReturnDecompressor(zlibDecompressor);
            // Now create a GZip text file.
            string         tmpDir = Runtime.GetProperty("test.build.data", "/tmp/");
            Path           f      = new Path(new Path(tmpDir), "testGzipLongOverflow.bin.gz");
            BufferedWriter bw     = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream
                                                                                  (new FileOutputStream(f.ToString()))));
            int Nbuf = 1024 * 4 + 1;

            char[] buf = new char[1024 * 1024];
            for (int i = 0; i < buf.Length; i++)
            {
                buf[i] = '\0';
            }
            for (int i_1 = 0; i_1 < Nbuf; i_1++)
            {
                bw.Write(buf);
            }
            bw.Close();
            // Now read it back, using the CodecPool to establish the
            // decompressor to use.
            CompressionCodecFactory ccf          = new CompressionCodecFactory(conf);
            CompressionCodec        codec        = ccf.GetCodec(f);
            Decompressor            decompressor = CodecPool.GetDecompressor(codec);
            FileSystem  fs  = FileSystem.GetLocal(conf);
            InputStream @is = fs.Open(f);

            @is = codec.CreateInputStream(@is, decompressor);
            BufferedReader br = new BufferedReader(new InputStreamReader(@is));

            for (int j = 0; j < Nbuf; j++)
            {
                int n = br.Read(buf);
                Assert.Equal("got wrong read length!", n, buf.Length);
                for (int i_2 = 0; i_2 < buf.Length; i_2++)
                {
                    Assert.Equal("got wrong byte!", buf[i_2], '\0');
                }
            }
            br.Close();
        }
        /// <exception cref="System.Exception"/>
        public virtual void PrintMatchedGraphsForPattern(string filename, int maxGraphsPerPattern)
        {
            BufferedWriter w = new BufferedWriter(new FileWriter(filename));

            foreach (KeyValuePair <SemgrexPattern, IList <Pair <string, SemanticGraph> > > en in matchedGraphsForPattern)
            {
                w.Write("\n\nFor Pattern: " + en.Key.Pattern() + "\n");
                int num = 0;
                foreach (Pair <string, SemanticGraph> gEn in en.Value)
                {
                    num++;
                    if (num > maxGraphsPerPattern)
                    {
                        break;
                    }
                    w.Write(gEn.First() + "\n" + gEn.Second().ToFormattedString() + "\n\n");
                }
            }
            w.Close();
        }
Exemplo n.º 30
0
 /// <summary>This prints out a ConcatVector by mapping to the namespace, to make debugging learning algorithms easier.</summary>
 /// <param name="vector">the vector to print</param>
 /// <param name="bw">the output stream to write to</param>
 /// <exception cref="System.IO.IOException"/>
 public virtual void DebugVector(ConcatVector vector, BufferedWriter bw)
 {
     foreach (string key in featureToIndex.Keys)
     {
         bw.Write(key);
         bw.Write(":\n");
         int i = featureToIndex[key];
         if (vector.IsComponentSparse(i))
         {
             DebugFeatureValue(key, vector.GetSparseIndex(i), vector, bw);
         }
         else
         {
             double[] arr = vector.GetDenseComponent(i);
             for (int j = 0; j < arr.Length; j++)
             {
                 DebugFeatureValue(key, j, vector, bw);
             }
         }
     }
 }
Exemplo n.º 31
0
        private void BtnWindowsMapExport_Click(object sender, EventArgs e)
        {
            string Map     = dataService.GetAllMapLines().ToJson();
            string MapName = DataBase.Currentversion.VersionName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".map";

            Java.IO.File   file = new Java.IO.File(DictoryPath, MapName);
            BufferedWriter bw   = new BufferedWriter(new FileWriter(file, false));

            bw.Write(Map);
            bw.Flush();
            textViewTips.Text = "地图导出成功";
        }