protected JsonObject ParseURL(string urlstring) { Log.Debug(TAG, "Parse URL: " + urlstring); InputStream inputStream = null; mPrefixUrl = mContext.Resources.GetString(Resource.String.prefix_url); try { Java.Net.URL url = new Java.Net.URL(urlstring); var urlConnection = url.OpenConnection(); inputStream = new BufferedInputStream(urlConnection.InputStream); var reader = new BufferedReader(new InputStreamReader( urlConnection.InputStream, "iso-8859-1"), 8); var sb = new StringBuilder(); string line = null; while ((line = reader.ReadLine()) != null) { sb.Append(line); } var json = sb.ToString(); return((JsonObject)JsonObject.Parse(json)); } catch (Exception e) { Log.Debug(TAG, "Failed to parse the json for media list", e); return(null); } finally { if (null != inputStream) { try { inputStream.Close(); } catch (IOException e) { Log.Debug(TAG, "Json feed closed", e); } } } }
public static string getCharset1(string fileName) { BufferedInputStream bin = new BufferedInputStream(new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate)); int p = (bin.Read() << 8) + bin.Read(); string code; switch (p) { case 0xefbb: code = "UTF-8"; break; case 0xfffe: code = "Unicode"; break; case 0xfeff: code = "UTF-16BE"; break; default: code = "GBK"; break; } return(code); }
/// <summary> /// 解压文件 /// </summary> /// <param name="inputZip"></param> /// <param name="destinationDirectory"></param> public static void UnzipFile(string inputZip, string destinationDirectory) { int buffer = 2048; List <string> zipFiles = new List <string>(); File sourceZipFile = new File(inputZip); File unzipDirectory = new File(destinationDirectory); CreateDir(unzipDirectory.AbsolutePath); ZipFile zipFile; zipFile = new ZipFile(sourceZipFile, ZipFile.OpenRead); IEnumeration zipFileEntries = zipFile.Entries(); while (zipFileEntries.HasMoreElements) { ZipEntry entry = (ZipEntry)zipFileEntries.NextElement(); string currentEntry = entry.Name; File destFile = new File(unzipDirectory, currentEntry); if (currentEntry.EndsWith(Constant.SUFFIX_ZIP)) { zipFiles.Add(destFile.AbsolutePath); } File destinationParent = destFile.ParentFile; CreateDir(destinationParent.AbsolutePath); if (!entry.IsDirectory) { if (destFile != null && destFile.Exists()) { continue; } BufferedInputStream inputStream = new BufferedInputStream(zipFile.GetInputStream(entry)); int currentByte; // buffer for writing file byte[] data = new byte[buffer]; var fos = new System.IO.FileStream(destFile.AbsolutePath, System.IO.FileMode.OpenOrCreate); BufferedOutputStream dest = new BufferedOutputStream(fos, buffer); while ((currentByte = inputStream.Read(data, 0, buffer)) != -1) { dest.Write(data, 0, currentByte); } dest.Flush(); dest.Close(); inputStream.Close(); } } zipFile.Close(); foreach (var zipName in zipFiles) { UnzipFile(zipName, destinationDirectory + File.SeparatorChar + zipName.Substring(0, zipName.LastIndexOf(Constant.SUFFIX_ZIP))); } }
private static string GetFileFromUrl(string fromUrl, string toFile) { try { URL url = new URL(fromUrl); URLConnection connection = url.OpenConnection(); connection.Connect(); //int fileLength = connection.GetContentLength(); // download the file InputStream input = new BufferedInputStream(url.OpenStream()); OutputStream output = new FileOutputStream(toFile); var data = new byte[1024]; long total = 0; int count; while ((count = input.Read(data)) != -1) { total += count; ////PublishProgress((int)(total * 100 / fileLength)); output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); } catch (Exception e) { Log.Error("YourApp", e.Message); } return(toFile); }
protected MovieJson[] ParseURL(string urlstring) { Log.Debug(TAG, "Parse URL: " + urlstring); InputStream inputStream = null; try { Java.Net.URL url = new Java.Net.URL(urlstring); var urlConnection = url.OpenConnection(); inputStream = new BufferedInputStream(urlConnection.InputStream); var reader = new BufferedReader(new InputStreamReader( urlConnection.InputStream, "iso-8859-1"), 8); var sb = new StringBuilder(); string line = null; while ((line = reader.ReadLine()) != null) { sb.Append(line); } var json = sb.ToString(); var response = JsonConvert.DeserializeObject <MoviesResponse> (json); return(response.Results); } catch (Exception e) { Log.Debug(TAG, "Failed to parse the json for media list", e); return(null); } finally { if (null != inputStream) { try { inputStream.Close(); } catch (IOException e) { Log.Debug(TAG, "Json feed closed", e); } } } }
/// <exception cref="System.IO.IOException"/> public BZip2CompressionInputStream(InputStream @in, long start, long end, SplittableCompressionCodec.READ_MODE readMode) : base(@in, start, end) { // class data starts here// // Following state machine handles different states of compressed stream // position // HOLD : Don't advertise compressed stream position // ADVERTISE : Read 1 more character and advertise stream position // See more comments about it before updatePos method. // class data ends here// needsReset = false; bufferedIn = new BufferedInputStream(base.@in); this.startingPos = base.GetPos(); this.readMode = readMode; if (this.startingPos == 0) { // We only strip header if it is start of file bufferedIn = ReadStreamHeader(); } input = new CBZip2InputStream(bufferedIn, readMode); if (this.isHeaderStripped) { input.UpdateReportedByteCount(HeaderLen); } if (this.isSubHeaderStripped) { input.UpdateReportedByteCount(SubHeaderLen); } this.UpdatePos(false); }
/// <summary> /// Downloads the file from URL but stops if keepDownloading becomes false. /// </summary> /// <returns><c>true</c>, if file from UR was downloaded, <c>false</c> otherwise.</returns> /// <param name="context">Context.</param> /// <param name="url">URL.</param> /// <param name="newFileNameWithExtension">New file name with extension.</param> /// <param name="keepDownloading">Keep downloading.</param> public static bool DownloadFileFromURL(global::Android.Content.Context context, string url, string newFileNameWithExtension, ref bool keepDownloading) { URL address = new URL(url); var conn = address.OpenConnection(); System.IO.Stream inputStream = conn.InputStream; BufferedInputStream bis = new BufferedInputStream(inputStream); Org.Apache.Http.Util.ByteArrayBuffer bab = new Org.Apache.Http.Util.ByteArrayBuffer(64); int current = 0; while ((current = bis.Read()) != -1) { if (keepDownloading == false) { bab.Clear(); return(false); } bab.Append((byte)current); } var fos = context.OpenFileOutput(newFileNameWithExtension, global::Android.Content.FileCreationMode.Private); byte[] babByte = bab.ToByteArray(); fos.Write(babByte, 0, babByte.Length); fos.Close(); return(true); }
protected override string RunInBackground(params string[] @params) { string strongPath = Android.OS.Environment.ExternalStorageDirectory.Path; string filePath = System.IO.Path.Combine(strongPath, "download.jpg"); int count; try { URL url = new URL(@params[0]); URLConnection connection = url.OpenConnection(); connection.Connect(); int LengthOfFile = connection.ContentLength; InputStream input = new BufferedInputStream(url.OpenStream(), LengthOfFile); OutputStream output = new FileOutputStream(filePath); byte[] data = new byte[1024]; long total = 0; while ((count = input.Read(data)) != -1) { total += count; PublishProgress("" + (int)((total / 100) / LengthOfFile)); output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); } catch (Exception e) { } return(null); }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="System.IO.IOException"></exception> public override ObjectStream OpenStream() { InputStream @in = this._enclosing.ptr.OpenEntryStream(); @in = new BufferedInputStream(@in); return(new ObjectStream.Filter(this.GetType(), this.GetSize(), @in)); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception public virtual string getRaw(string hostname, int port, string uriPath, string mimeType) { URI uri = new URI(useSsl ? "https" : "http", null, hostname, port, uriPath, null, null); HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); connection.addRequestProperty("Accept", mimeType); var str = new StringBuilder(); Stream @in = new BufferedInputStream(connection.getInputStream()); try { for (;;) { var b = @in.Read(); if (b < 0) { break; } str.Append((char) (b & 0xff)); } } finally { CloseableUtils.closeQuietly(@in); } return str.ToString(); }
private static sbyte[] readFile(Jfile file) { InputStream @in = new BufferedInputStream(new FileInputStream(file)); ByteArrayOutputStream bytes = new ByteArrayOutputStream(new FileStream(file.Name, FileMode.Open)); try { sbyte[] buffer = new sbyte[1024]; int length; while ((length = @in.read(buffer, 0, buffer.Length)) > 0) { bytes.write(buffer, 0, length); } } finally { try { @in.close(); } catch (IOException) { // sorry that this can fail! } } return(bytes.toSbyteArray()); }
protected override string RunInBackground(params string[] @params) { var storagePath = Android.OS.Environment.ExternalStorageDirectory.Path; var filePath = System.IO.Path.Combine(storagePath, $"{fileName}.jpg"); try { URL url = new URL(@params[0]); URLConnection connection = url.OpenConnection(); connection.Connect(); int lengthOfFile = connection.ContentLength; InputStream input = new BufferedInputStream(url.OpenStream(), lengthOfFile); OutputStream output = new FileOutputStream(filePath); byte[] data = new byte[1024]; long total = 0; int count = 0; while ((count = input.Read(data)) != -1) { total += count; PublishProgress($"{(int)(total / 100) / lengthOfFile}"); output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); return(string.Empty); } catch (Exception ex) { return(ex.Message); } }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="System.IO.IOException"></exception> public override ObjectStream OpenStream() { WindowCursor wc = new WindowCursor(db); InputStream @in; try { @in = new PackInputStream(pack, objectOffset + headerLength, wc); } catch (IOException) { // If the pack file cannot be pinned into the cursor, it // probably was repacked recently. Go find the object // again and open the stream from that location instead. // return(wc.Open(GetObjectId(), type).OpenStream()); } @in = new BufferedInputStream(new InflaterInputStream(@in, wc.Inflater(), 8192), 8192); // // // // // return(new ObjectStream.Filter(type, size, @in)); }
private Object Post(string parameters) { try { conn = (HttpURLConnection)url.OpenConnection(); conn.RequestMethod = "POST"; conn.DoOutput = true; conn.DoInput = true; conn.Connect(); Android.Util.Log.Debug("SendToServer", "parametros " + parameters); byte[] bytes = Encoding.ASCII.GetBytes(parameters); OutputStream outputStream = new BufferedOutputStream(conn.OutputStream); outputStream.Write(bytes); outputStream.Flush(); outputStream.Close(); InputStream inputStream = new BufferedInputStream(conn.InputStream); return(ReadString(inputStream)); } catch (IOException e) { Android.Util.Log.Debug("SendToServer", "Problems to send data to server!! " + e.Message); return(false); } finally { conn.Disconnect(); } }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="System.IO.IOException"></exception> public override ObjectStream OpenStream() { // If the object was recently unpacked, its available loose. // The loose format is going to be faster to access than a // delta applied on top of a base. Use that whenever we can. // ObjectId myId = GetObjectId(); WindowCursor wc = new WindowCursor(db); ObjectLoader ldr = db.OpenObject2(wc, myId.Name, myId); if (ldr != null) { return(ldr.OpenStream()); } InputStream @in = Open(wc); @in = new BufferedInputStream(@in, 8192); // While we inflate the object, also deflate it back as a loose // object. This will later be cleaned up by a gc pass, but until // then we will reuse the loose form by the above code path. // int myType = GetType(); long mySize = GetSize(); ObjectDirectoryInserter odi = ((ObjectDirectoryInserter)db.NewInserter()); FilePath tmp = odi.NewTempFile(); DeflaterOutputStream dOut = odi.Compress(new FileOutputStream(tmp)); odi.WriteHeader(dOut, myType, mySize); @in = new TeeInputStream(@in, dOut); return(new _Filter_195(this, odi, wc, tmp, myId, myType, mySize, @in)); }
public BufferedInputStream read(int i) { BufferedInputStream inputStream = new BufferedInputStream(); inputStream._init_(read(), i); return(inputStream); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public static void copyfile(String source, String destination) throws org.maltparser.core.exception.MaltChainedException public static void copyfile(string source, string destination) { try { sbyte[] readBuffer = new sbyte[BUFFER]; BufferedInputStream bis = new BufferedInputStream(new FileStream(source, FileMode.Open, FileAccess.Read)); BufferedOutputStream bos = new BufferedOutputStream(new FileStream(destination, FileMode.Create, FileAccess.Write), BUFFER); int n = 0; while ((n = bis.read(readBuffer, 0, BUFFER)) != -1) { bos.write(readBuffer, 0, n); } bos.flush(); bos.close(); bis.close(); } catch (FileNotFoundException e) { throw new MaltChainedException("The destination file '" + destination + "' cannot be created when coping the file. ", e); } catch (IOException e) { throw new MaltChainedException("The source file '" + source + "' cannot be copied to destination '" + destination + "'. ", e); } }
internal QueueConfigurationParser(string confFile, bool areAclsEnabled) { //Default root. //xml tags for mapred-queues.xml // The value read from queues config file for this tag is not used at all. // To enable queue acls and job acls, mapreduce.cluster.acls.enabled is // to be set in mapred-site.xml aclsEnabled = areAclsEnabled; FilePath file = new FilePath(confFile).GetAbsoluteFile(); if (!file.Exists()) { throw new RuntimeException("Configuration file not found at " + confFile); } InputStream @in = null; try { @in = new BufferedInputStream(new FileInputStream(file)); LoadFrom(@in); } catch (IOException ioe) { throw new RuntimeException(ioe); } finally { IOUtils.CloseStream(@in); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void read(String fileName) throws java.io.IOException public virtual void read(string fileName) { System.IO.FileStream fileInputStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream); BufferedInputStream bufferedInputStream = new BufferedInputStream(gzipInputStream); StateInputStream stream = new StateInputStream(bufferedInputStream); if (log.InfoEnabled) { Console.WriteLine(string.Format("Reading state from file '{0}'", fileName)); } try { read(stream); if (stream.read() >= 0) { Console.WriteLine(string.Format("State file '{0}' containing too much data", fileName)); } } finally { stream.close(); } //if (log.DebugEnabled) { Console.WriteLine(string.Format("Done reading state from file '{0}'", fileName)); } }
public static void copy(Stream inputStream, File output) { OutputStream outputStream = null; var bufferedInputStream = new BufferedInputStream(inputStream); try { outputStream = new FileOutputStream(output); int read = 0; byte[] bytes = new byte[1024]; while ((read = bufferedInputStream.Read(bytes)) != -1) { outputStream.Write(bytes, 0, read); } } finally { try { if (inputStream != null) { inputStream.Close(); } } finally { if (outputStream != null) { outputStream.Close(); } } } }
public static byte[] readFile(String filePath) { byte[] contents; Java.IO.File file = new Java.IO.File(filePath); int size = (int)file.Length(); contents = new byte[size]; try { FileStream inputStream = new FileStream(filePath, FileMode.OpenOrCreate); Java.IO.BufferedOutputStream bos = new Java.IO.BufferedOutputStream(inputStream); BufferedInputStream buf = new BufferedInputStream(inputStream); try { buf.Read(contents); buf.Close(); } catch (Java.IO.IOException e) { e.PrintStackTrace(); } } catch (Java.IO.FileNotFoundException e) { e.PrintStackTrace(); } return(contents); }
public void UnZip(string zipFileLocation, string destinationRootFolder, string zipRootToRemove) { try { var zipFile = new ZipFile(zipFileLocation); var zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { var zipEntry = (ZipEntry)zipFileEntries.nextElement(); var name = zipEntry.getName().Replace(zipRootToRemove, "").Replace("/", "\\").TrimStart('/').TrimStart('\\'); var p = this.fileSystem.Path.Combine(destinationRootFolder, name); if (zipEntry.isDirectory()) { if (!this.fileSystem.Directory.Exists(p)) { this.fileSystem.Directory.CreateDirectory(p); } ; } else { using (var bis = new BufferedInputStream(zipFile.getInputStream(zipEntry))) { var buffer = new byte[2048]; var count = buffer.GetLength(0); using (var fos = new FileOutputStream(p)) { using (var bos = new BufferedOutputStream(fos, count)) { int size; while ((size = bis.read(buffer, 0, count)) != -1) { bos.write(buffer, 0, size); } bos.flush(); bos.close(); } } bis.close(); } } } zipFile.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { var t = e.ToString(); } }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="System.IO.IOException"></exception> public override ObjectStream OpenStream() { long contentLength = this._enclosing.ptr.GetEntryContentLength(); InputStream @in = this._enclosing.ptr.OpenEntryStream(); @in = new BufferedInputStream(@in); return(new ObjectStream.Filter(this.GetType(), contentLength, @in)); }
/// <exception cref="System.IO.IOException"/> public virtual Annotation CreateFromFile(string filename) { InputStream stream = new BufferedInputStream(new FileInputStream(filename)); Annotation anno = Create(stream); IOUtils.CloseIgnoringExceptions(stream); return(anno); }
//*************************************************************************************************** //******************FUNCION QUE SE ENCARGA DEL PROCESO DE DESCARGA DE ARCHIVO*********************** //*************************************************************************************************** void DescargaArchivo(ProgressCircleView tem_pcv, string url_archivo) { //OBTENEMOS LA RUTA DONDE SE ENCUENTRA LA CARPETA PICTURES DE NUESTRO DISPOSITIVO Y LE CONCTENAMOS //EL NOMBRE DE UNA CARPETA NUEVA CARPETA, ES AQUI DONDE GUADAREMOS EL ARCHIVO A DESCARGAR string filePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath + "/DescargaImagen/"; Java.IO.File directory = new Java.IO.File(filePath); //VERIFICAMOS SI LA CARPETA EXISTE, SI NO LA CREAMOS if (directory.Exists() == false) { directory.Mkdir(); } //ESTABLECEMOS LA UBICACION DE NUESTRO ARCHIVO A DESCARGAR URL url = new URL(url_archivo); //CABRIMOS UNA CONEXION CON EL ARCHIVO URLConnection conexion = url.OpenConnection(); conexion.Connect(); //OBTENEMOS EL TAMAÑO DEL ARCHIVO A DESCARGAR int lenghtOfFile = conexion.ContentLength; //CREAMOS UN INPUTSTREAM PARA PODER EXTRAER EL ARCHIVO DE LA CONEXION InputStream input = new BufferedInputStream(url.OpenStream()); //ASIGNAMOS LA RUTA DONDE SE GUARDARA EL ARCHIVO, Y ASIGNAMOS EL NOMBRE CON EL QUE SE DESCARGAR EL ARCHIVO //PARA ESTE CASO CONSERVA EL MISMO NOMBRE string NewFile = directory.AbsolutePath + "/" + url_archivo.Substring(url_archivo.LastIndexOf("/") + 1); //CREAMOS UN OUTPUTSTREAM EN EL CUAL UTILIZAREMOS PARA CREAR EL ARCHIVO QUE ESTAMOS DESCARGANDO OutputStream output = new FileOutputStream(NewFile); byte[] data = new byte[lenghtOfFile]; long total = 0; int count; //COMENSAMOS A LEER LOS DATOS DE NUESTRO INPUTSTREAM while ((count = input.Read(data)) != -1) { total += count; //CON ESTA OPCION REPORTAMOS EL PROGRESO DE LA DESCARGA EN PORCENTAJE A NUESTRO CONTROL //QUE SE ENCUENTRA EN EL HILO PRINCIPAL RunOnUiThread(() => tem_pcv.setPorcentaje((int)((total * 100) / lenghtOfFile))); //ESCRIBIMOS LOS DATOS DELIDOS ES NUESTRO OUTPUTSTREAM output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); //INDICAMOS A NUESTRO PROGRESS QUE SE HA COMPLETADO LA DESCARGA AL 100% RunOnUiThread(() => tem_pcv.setPorcentaje(100)); }
/// <exception cref="System.IO.IOException"/> private void InternalReset() { if (needsReset) { needsReset = false; BufferedInputStream bufferedIn = ReadStreamHeader(); input = new CBZip2InputStream(bufferedIn, this.readMode); } }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="System.IO.IOException"></exception> public override ObjectStream OpenStream() { FileInputStream @in = new FileInputStream(p); long sz = @in.GetChannel().Size(); int type = this.GetType(); BufferedInputStream b = new BufferedInputStream(@in); return(new ObjectStream.Filter(type, sz, b)); }
public static void startReplay(string filename) { if (captureInProgress) { VideoEngine.log_Renamed.error("Ignoring startReplay, capture is in progress"); return; } VideoEngine.log_Renamed.info("Starting replay: " + filename); try { System.IO.Stream @in = new BufferedInputStream(new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read)); while (@in.available() > 0) { CaptureHeader header = CaptureHeader.read(@in); int packetType = header.PacketType; switch (packetType) { case CaptureHeader.PACKET_TYPE_LIST: CaptureList list = CaptureList.read(@in); list.commit(); break; case CaptureHeader.PACKET_TYPE_RAM: CaptureRAM ramFragment = CaptureRAM.read(@in); ramFragment.commit(); break; // deprecated case CaptureHeader.PACKET_TYPE_DISPLAY_DETAILS: CaptureDisplayDetails displayDetails = CaptureDisplayDetails.read(@in); displayDetails.commit(); break; case CaptureHeader.PACKET_TYPE_FRAMEBUF_DETAILS: // don't replay this one immediately, wait until after the list has finished executing replayFrameBufDetails = CaptureFrameBufDetails.read(@in); break; default: throw new Exception("Unknown packet type " + packetType); } } @in.Close(); } catch (Exception e) { VideoEngine.log_Renamed.error("Failed to start replay: " + e.Message); Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } }
public virtual void TestStreamLimiter() { FilePath LimiterTestFile = new FilePath(TestDir, "limiter.test"); FileOutputStream fos = new FileOutputStream(LimiterTestFile); try { fos.Write(unchecked ((int)(0x12))); fos.Write(unchecked ((int)(0x12))); fos.Write(unchecked ((int)(0x12))); } finally { fos.Close(); } FileInputStream fin = new FileInputStream(LimiterTestFile); BufferedInputStream bin = new BufferedInputStream(fin); FSEditLogLoader.PositionTrackingInputStream tracker = new FSEditLogLoader.PositionTrackingInputStream (bin); try { tracker.SetLimit(2); tracker.Mark(100); tracker.Read(); tracker.Read(); try { tracker.Read(); NUnit.Framework.Assert.Fail("expected to get IOException after reading past the limit" ); } catch (IOException) { } tracker.Reset(); tracker.Mark(100); byte[] arr = new byte[3]; try { tracker.Read(arr); NUnit.Framework.Assert.Fail("expected to get IOException after reading past the limit" ); } catch (IOException) { } tracker.Reset(); arr = new byte[2]; tracker.Read(arr); } finally { tracker.Close(); } }
public static ImmutableFst loadModel(InputStream inputStream) { BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); ObjectInputStream objectInputStream = new ObjectInputStream(bufferedInputStream); ImmutableFst result = ImmutableFst.readImmutableFst(objectInputStream); objectInputStream.close(); bufferedInputStream.close(); inputStream.close(); return(result); }
public virtual void AES256IGEDecrypt(string sourceFile, string destFile, byte[] iv, byte[] key) { int num1; File file = new File(sourceFile); File file2 = new File(destFile); AESFastEngine engine = new AESFastEngine(); engine.init(false, new KeyParameter(key)); byte[] buffer = CryptoUtils.substring(iv, 0x10, 0x10); byte[] buffer2 = CryptoUtils.substring(iv, 0, 0x10); BufferedInputStream.__ <clinit>(); BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream stream2 = new BufferedOutputStream(new FileOutputStream(file2)); byte[] buffer3 = new byte[0x10]; Label_0060: num1 = stream.read(buffer3); if (num1 <= 0) { stream2.flush(); stream2.close(); stream.close(); } else { byte[] @in = new byte[0x10]; int index = 0; while (true) { if (index >= 0x10) { break; } @in[index] = (byte)((sbyte)(buffer3[index] ^ buffer[index])); index++; } engine.processBlock(@in, 0, @in, 0); index = 0; while (true) { if (index >= 0x10) { break; } @in[index] = (byte)((sbyte)(@in[index] ^ buffer2[index])); index++; } buffer2 = buffer3; buffer = @in; buffer3 = new byte[0x10]; stream2.write(@in); goto Label_0060; } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public MessageList paymentRequest(DirectPaymentRequest directPaymentRequest, EasypayConfig config) throws java.net.MalformedURLException public virtual MessageList paymentRequest(DirectPaymentRequest directPaymentRequest, EasypayConfig config) { URL url = new URL("https://" + config.Host); string httpRequestMethod = "POST"; string contentHash = "xxx"; string contentType = "??"; string date = ""; string path = ""; HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.RequestMethod = httpRequestMethod; urlConnection.setRequestProperty("Content-Type", contentType); // urlConnection.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length)); urlConnection.UseCaches = false; urlConnection.DoInput = true; urlConnection.DoOutput = true; System.IO.Stream @out = new BufferedOutputStream(urlConnection.OutputStream); // writeStream(out); System.IO.Stream @in = new BufferedInputStream(urlConnection.InputStream); // readStream(in); } catch (IOException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return new MessageList(); }
public static void copy(Stream inputStream, File output) { OutputStream outputStream = null; var bufferedInputStream = new BufferedInputStream(inputStream); try { outputStream = new FileOutputStream(output); int read = 0; byte[] bytes = new byte[1024]; while ((read = bufferedInputStream.Read(bytes)) != -1){ outputStream.Write(bytes, 0, read); } } finally { try { if (inputStream != null) { inputStream.Close(); } } finally { if (outputStream != null) { outputStream.Close(); } } } }
protected override Java.Lang.Object DoInBackground (params Java.Lang.Object[] @params) { //REALIZAMOS EL PROCESO DE DESCARGA DEL ARCHIVO try{ string filePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath+"/DescargaImagen/" ; Java.IO.File directory = new Java.IO.File (filePath); if(directory.Exists() ==false) { directory.Mkdir(); } //RECUPERAMOS LA DIRECCION DEL ARCHIVO QUE DESEAMOS DESCARGAR string url_link = @params [0].ToString (); URL url = new URL(url_link); URLConnection conexion = url.OpenConnection(); conexion.Connect (); int lenghtOfFile = conexion.ContentLength; InputStream input = new BufferedInputStream(url.OpenStream()); string NewImageFile = directory.AbsolutePath+ "/"+ url_link.Substring (url_link.LastIndexOf ("/") + 1); OutputStream output = new FileOutputStream(NewImageFile); byte[] data= new byte[lenghtOfFile]; int count; while ((count = input.Read(data)) != -1) { output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); return true; }catch { return false; } }
protected JsonObject ParseURL (string urlstring) { Log.Debug (TAG, "Parse URL: " + urlstring); InputStream inputStream = null; mPrefixUrl = mContext.Resources.GetString (Resource.String.prefix_url); try { Java.Net.URL url = new Java.Net.URL (urlstring); var urlConnection = url.OpenConnection (); inputStream = new BufferedInputStream (urlConnection.InputStream); var reader = new BufferedReader (new InputStreamReader ( urlConnection.InputStream, "iso-8859-1"), 8); var sb = new StringBuilder (); string line = null; while ((line = reader.ReadLine ()) != null) { sb.Append (line); } var json = sb.ToString (); return (JsonObject)JsonObject.Parse (json); } catch (Exception e) { Log.Debug (TAG, "Failed to parse the json for media list", e); return null; } finally { if (null != inputStream) { try { inputStream.Close (); } catch (IOException e) { Log.Debug (TAG, "Json feed closed", e); } } } }
//*************************************************************************************************** //******************FUNCION QUE SE ENCARGA DEL PROCESO DE DESCARGA DE ARCHIVO*********************** //*************************************************************************************************** void DescargaArchivo(ProgressCircleView tem_pcv, string url_archivo) { //OBTENEMOS LA RUTA DONDE SE ENCUENTRA LA CARPETA PICTURES DE NUESTRO DISPOSITIVO Y LE CONCTENAMOS //EL NOMBRE DE UNA CARPETA NUEVA CARPETA, ES AQUI DONDE GUADAREMOS EL ARCHIVO A DESCARGAR string filePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath+"/DescargaImagen/" ; Java.IO.File directory = new Java.IO.File (filePath); //VERIFICAMOS SI LA CARPETA EXISTE, SI NO LA CREAMOS if(directory.Exists() ==false) { directory.Mkdir(); } //ESTABLECEMOS LA UBICACION DE NUESTRO ARCHIVO A DESCARGAR URL url = new URL(url_archivo); //CABRIMOS UNA CONEXION CON EL ARCHIVO URLConnection conexion = url.OpenConnection(); conexion.Connect (); //OBTENEMOS EL TAMAÑO DEL ARCHIVO A DESCARGAR int lenghtOfFile = conexion.ContentLength; //CREAMOS UN INPUTSTREAM PARA PODER EXTRAER EL ARCHIVO DE LA CONEXION InputStream input = new BufferedInputStream(url.OpenStream()); //ASIGNAMOS LA RUTA DONDE SE GUARDARA EL ARCHIVO, Y ASIGNAMOS EL NOMBRE CON EL QUE SE DESCARGAR EL ARCHIVO //PARA ESTE CASO CONSERVA EL MISMO NOMBRE string NewFile = directory.AbsolutePath+ "/"+ url_archivo.Substring (url_archivo.LastIndexOf ("/") + 1); //CREAMOS UN OUTPUTSTREAM EN EL CUAL UTILIZAREMOS PARA CREAR EL ARCHIVO QUE ESTAMOS DESCARGANDO OutputStream output = new FileOutputStream(NewFile); byte[] data= new byte[lenghtOfFile]; long total = 0; int count; //COMENSAMOS A LEER LOS DATOS DE NUESTRO INPUTSTREAM while ((count = input.Read(data)) != -1) { total += count; //CON ESTA OPCION REPORTAMOS EL PROGRESO DE LA DESCARGA EN PORCENTAJE A NUESTRO CONTROL //QUE SE ENCUENTRA EN EL HILO PRINCIPAL RunOnUiThread(() => tem_pcv.setPorcentaje ((int)((total*100)/lenghtOfFile))); //ESCRIBIMOS LOS DATOS DELIDOS ES NUESTRO OUTPUTSTREAM output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); //INDICAMOS A NUESTRO PROGRESS QUE SE HA COMPLETADO LA DESCARGA AL 100% RunOnUiThread(() => tem_pcv.setPorcentaje (100)); }