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); }
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 = p switch { 0xefbb => "UTF-8", 0xfffe => "Unicode", 0xfeff => "UTF-16BE", _ => "GBK", }; return(code); }
/// <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) { 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); } }
/// <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))); } }
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 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); }
//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(); }
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); }
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); }
//*************************************************************************************************** //******************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)); }
private string DownloadFile(string sUrl, string filePath) { try { //get result from uri URL url = new Java.Net.URL(sUrl); URLConnection connection = url.OpenConnection(); connection.Connect(); // this will be useful so that you can show a tipical 0-100% // progress bar int lengthOfFile = connection.ContentLength; // download the file InputStream input = new BufferedInputStream(url.OpenStream(), 8192); // Output stream Log.WriteLine(LogPriority.Info, "DownloadFile FilePath ", filePath); OutputStream output = new FileOutputStream(filePath); byte[] data = new byte[1024]; long total = 0; int count; while ((count = input.Read(data)) != -1) { total += count; // publishing the progress.... // After this onProgressUpdate will be called //publishProgress("" + (int)((total * 100) / lengthOfFile)); if (total % 10 == 10) //log for every 10th increment { Log.WriteLine(LogPriority.Info, "DownloadFile Progress ", "" + (int)((total * 100) / lengthOfFile)); } // writing data to file output.Write(data, 0, count); } // flushing output output.Flush(); // closing streams output.Close(); input.Close(); } catch (Exception ex) { Log.WriteLine(LogPriority.Error, "DownloadFile Error", ex.Message); } return(filePath); }
/// <exception cref="System.IO.IOException"/> private BufferedInputStream ReadStreamHeader() { // We are flexible enough to allow the compressed stream not to // start with the header of BZ. So it works fine either we have // the header or not. if (base.@in != null) { bufferedIn.Mark(HeaderLen); byte[] headerBytes = new byte[HeaderLen]; int actualRead = bufferedIn.Read(headerBytes, 0, HeaderLen); if (actualRead != -1) { string header = new string(headerBytes, Charsets.Utf8); if (string.CompareOrdinal(header, Header) != 0) { bufferedIn.Reset(); } else { this.isHeaderStripped = true; // In case of BYBLOCK mode, we also want to strip off // remaining two character of the header. if (this.readMode == SplittableCompressionCodec.READ_MODE.Byblock) { actualRead = bufferedIn.Read(headerBytes, 0, SubHeaderLen); if (actualRead != -1) { this.isSubHeaderStripped = true; } } } } } if (bufferedIn == null) { throw new IOException("Failed to read bzip2 stream."); } return(bufferedIn); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private static long calculateCrc32HashOfFile(java.nio.file.Path source) throws java.io.IOException private static long CalculateCrc32HashOfFile(Path source) { CRC32 crc = new CRC32(); using (Stream inputStream = new BufferedInputStream(new FileStream(source.toFile(), FileMode.Open, FileAccess.Read))) { int cnt; while ((cnt = inputStream.Read()) != -1) { crc.update(cnt); } } return(crc.Value); }
public static FileType?DetectFileType([NotNull] BufferedInputStream inputStream) { int maxByteCount = _root.GetMaxDepth(); inputStream.Mark(maxByteCount); sbyte[] bytes = new sbyte[maxByteCount]; int bytesRead = inputStream.Read(bytes); if (bytesRead == -1) { throw new IOException("Stream ended before file's magic number could be determined."); } inputStream.Reset(); //noinspection ConstantConditions return(_root.Find(bytes)); }
//import eu.europa.ec.markt.dss.validation.asic.ASiCXMLDocumentValidator; //import eu.europa.ec.markt.dss.validation.pades.PDFDocumentValidator; //import eu.europa.ec.markt.dss.validation.xades.XMLDocumentValidator; /// <summary>Guess the document format and return an appropriate document</summary> /// <param name="document"></param> /// <returns></returns> /// <exception cref="System.IO.IOException"></exception> public static SignedDocumentValidator FromDocument(Document document) { InputStream input = null; try { input = new BufferedInputStream(document.OpenStream()); input.Mark(5); byte[] preamble = new byte[5]; int read = input.Read(preamble); input.Reset(); if (read < 5) { throw new RuntimeException("Not a signed document"); } string preambleString = Sharpen.Runtime.GetStringForBytes(preamble); if (Sharpen.Runtime.GetBytesForString(preambleString)[0] == unchecked ((int)(0x30) )) { try { return(new CMSDocumentValidator(document)); } catch (CmsException) { throw new IOException("Not a valid CAdES file"); } } else { throw new RuntimeException("Document format not recognized/handled"); } } finally { if (input != null) { try { input.Close(); } catch (IOException) { } } } }
/// <exception cref="System.IO.IOException"/> private FilePath MakeTestJar() { FilePath jarFile = new FilePath(TestRootDir, TestJarName); JarOutputStream jstream = new JarOutputStream(new FileOutputStream(jarFile)); InputStream entryInputStream = this.GetType().GetResourceAsStream(ClassName); ZipEntry entry = new ZipEntry("org/apache/hadoop/util/" + ClassName); jstream.PutNextEntry(entry); BufferedInputStream bufInputStream = new BufferedInputStream(entryInputStream, 2048 ); int count; byte[] data = new byte[2048]; while ((count = bufInputStream.Read(data, 0, 2048)) != -1) { jstream.Write(data, 0, count); } jstream.CloseEntry(); jstream.Close(); return(jarFile); }
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); } }
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(); } } } }
private static void FileToZip(File file, ZipOutputStream outputStream) { BufferedInputStream origin = null; try { var buffer = 2048; var data = new byte[buffer]; var fi = new FileStream(file.AbsolutePath, FileMode.Open); origin = new BufferedInputStream(fi, buffer); var entry = new ZipEntry(file.Name); outputStream.PutNextEntry(entry); int count; while ((count = origin.Read(data, 0, buffer)) != -1) { outputStream.Write(data, 0, count); } } finally { origin?.Close(); } }
/** * 扫描添加文件Entry * * @param base 基路径 * @param source 源文件 * @param zos Zip文件输出流 * @throws IOException */ private static void addEntry(string bbase, File source, ZipOutputStream zos) { // 按目录分级,形如:/aaa/bbb.txt string entry = bbase + source.Name; if (source.IsDirectory) { foreach (File file in source.ListFiles()) { // 递归列出目录下的所有文件,添加文件Entry addEntry(entry + "/", file, zos); } } else { System.IO.FileStream fis = null; BufferedInputStream bis = null; try { byte[] buffer = new byte[1024 * 10]; fis = new System.IO.FileStream(source.Path, System.IO.FileMode.Append); bis = new BufferedInputStream(fis, buffer.Length); int read = 0; zos.PutNextEntry(new ZipEntry(entry)); while ((read = bis.Read(buffer, 0, buffer.Length)) != -1) { zos.Write(buffer, 0, read); } zos.CloseEntry(); } finally { bis.Close(); fis.Close(); } } }
// it should not throw an exception /// <exception cref="System.IO.IOException"/> private FilePath MakeClassLoaderTestJar(params string[] clsNames) { FilePath jarFile = new FilePath(TestRootDir, TestJar2Name); JarOutputStream jstream = new JarOutputStream(new FileOutputStream(jarFile)); foreach (string clsName in clsNames) { string name = clsName.Replace('.', '/') + ".class"; InputStream entryInputStream = this.GetType().GetResourceAsStream("/" + name); ZipEntry entry = new ZipEntry(name); jstream.PutNextEntry(entry); BufferedInputStream bufInputStream = new BufferedInputStream(entryInputStream, 2048 ); int count; byte[] data = new byte[2048]; while ((count = bufInputStream.Read(data, 0, 2048)) != -1) { jstream.Write(data, 0, count); } jstream.CloseEntry(); } jstream.Close(); return(jarFile); }
/// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="mirrorNames"></param> /// <param name="mirrorUrls"></param> /// <param name="mirror"></param> /// <param name="title"></param> /// <param name="path">FULL PATH</param> /// <param name="poster"></param> /// <param name="fileName"></param> /// <param name="beforeTxt"></param> /// <param name="openWhenDone"></param> /// <param name="showNotificaion"></param> /// <param name="showDoneNotificaion"></param> /// <param name="showDoneAsToast"></param> /// <param name="resumeIntent"></param> public static void HandleIntent(int id, List <BasicMirrorInfo> mirrors, int mirror, string title, string path, string poster, string beforeTxt, bool openWhenDone, bool showNotificaion, bool showDoneNotificaion, bool showDoneAsToast, bool resumeIntent) { const int UPDATE_TIME = 1; try { isStartProgress[id] = true; print("START DLOAD::: " + id); if (isPaused.ContainsKey(id)) { //if (isPaused[id] == 2) { // isPaused.Remove(id); // print("YEET DELETED KEEEE"); return; // } } var context = Application.Context; //$"{nameof(id)}={id}|||{nameof(title)}={title}|||{nameof(path)}={path}|||{nameof(poster)}={poster}|||{nameof(fileName)}={fileName}|||{nameof(beforeTxt)}={beforeTxt}|||{nameof(openWhenDone)}={openWhenDone}|||{nameof(showDoneNotificaion)}={showDoneNotificaion}|||{nameof(showDoneAsToast)}={showDoneAsToast}|||"); int progress = 0; int bytesPerSec = 0; void UpdateDloadNot(string progressTxt) { //poster != "" if (!isPaused.ContainsKey(id)) { isPaused[id] = 0; } try { int isPause = isPaused[id]; bool canPause = isPause == 0; if (isPause != 2) { ShowLocalNot(new LocalNot() { actions = new List <LocalAction>() { new LocalAction() { action = $"handleDownload|||id={id}|||dType={(canPause ? 1 : 0)}|||", name = canPause ? "Pause" : "Resume" }, new LocalAction() { action = $"handleDownload|||id={id}|||dType=2|||", name = "Stop" } }, mediaStyle = false, bigIcon = poster, title = $"{title} - {ConvertBytesToAny(bytesPerSec / UPDATE_TIME, 2, 2)} MB/s", autoCancel = false, showWhen = false, onGoing = canPause, id = id, smallIcon = PublicNot, progress = progress, body = progressTxt }, context); //canPause } } catch (Exception _ex) { print("ERRORLOADING PROGRESS:::" + _ex); } } void ShowDone(bool succ, string overrideText = null) { print("DAAAAAAAAAASHOW DONE" + succ); if (succ) { App.RemoveKey(DOWNLOAD_KEY, id.ToString()); App.RemoveKey(DOWNLOAD_KEY_INTENT, id.ToString()); } if (showDoneNotificaion) { print("DAAAAAAAAAASHOW DONE!!!!"); Device.BeginInvokeOnMainThread(() => { try { print("DAAAAAAAAAASHOW DONE222"); ShowLocalNot(new LocalNot() { mediaStyle = poster != "", bigIcon = poster, title = title, autoCancel = true, onGoing = false, id = id, smallIcon = PublicNot, body = overrideText ?? (succ ? "Download done!" : "Download Failed") }, context); // ((e.Cancelled || e.Error != null) ? "Download Failed!" } catch (Exception _ex) { print("SUPERFATALEX: " + _ex); } }); //await Task.Delay(1000); // 100% sure that it is downloaded OnSomeDownloadFinished?.Invoke(null, EventArgs.Empty); } else { print("DONT SHOW WHEN DONE"); } // Toast.MakeText(context, "PG DONE!!!", ToastLength.Long).Show(); } void StartT() { isStartProgress[id] = true; if (isPaused.ContainsKey(id)) { //if (isPaused[id] == 2) { // isPaused.Remove(id); return; // } } Thread t = new Thread(() => { print("START:::"); string json = JsonConvert.SerializeObject(new DownloadHandleNot() { id = id, mirrors = mirrors, showDoneAsToast = showDoneAsToast, openWhenDone = openWhenDone, showDoneNotificaion = showDoneNotificaion, beforeTxt = beforeTxt, mirror = mirror, path = path, poster = poster, showNotificaion = showNotificaion, title = title }); App.SetKey(DOWNLOAD_KEY_INTENT, id.ToString(), json); var mirr = mirrors[mirror]; string url = mirr.mirror; string urlName = mirr.name; string referer = mirr.referer ?? ""; bool isM3u8 = url.Contains(".m3u8"); if ((int)Android.OS.Build.VERSION.SdkInt > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().PermitAll().Build(); StrictMode.SetThreadPolicy(policy); } long total = 0; int fileLength = 0; void UpdateProgress() { UpdateDloadNot($"{beforeTxt.Replace("{name}", urlName)}{progress} % ({ConvertBytesToAny(total, 1, 2)} MB/{ConvertBytesToAny(fileLength, 1, 2)} MB)"); } void UpdateFromId(object sender, int _id) { if (_id == id) { UpdateProgress(); } } bool removeKeys = true; var rFile = new Java.IO.File(path); try { // CREATED DIRECTORY IF NEEDED try { Java.IO.File __file = new Java.IO.File(path); __file.Mkdirs(); } catch (Exception _ex) { print("FAILED:::" + _ex); } URL _url = new URL(url); URLConnection connection = _url.OpenConnection(); print("SET CONNECT ::"); if (!rFile.Exists()) { print("FILE DOSENT EXITS"); rFile.CreateNewFile(); } else { if (resumeIntent) { total = rFile.Length(); connection.SetRequestProperty("Range", "bytes=" + rFile.Length() + "-"); } else { rFile.Delete(); rFile.CreateNewFile(); } } print("SET CONNECT ::2"); connection.SetRequestProperty("Accept-Encoding", "identity"); if (referer != "") { connection.SetRequestProperty("Referer", referer); } int clen = 0; if (isM3u8) { clen = 1; } else { bool Completed = ExecuteWithTimeLimit(TimeSpan.FromMilliseconds(10000), () => { connection.Connect(); clen = connection.ContentLength; if (clen < 5000000 && !path.Contains("/YouTube/")) // min of 5 MB { clen = 0; } }); if (!Completed) { print("FAILED MASS"); clen = 0; } print("SET CONNECT ::3"); } print("TOTALLLLL::: " + clen); if (clen == 0) { if (isStartProgress.ContainsKey(id)) { isStartProgress.Remove(id); } if (mirror < mirrors.Count - 1 && progress < 2 && rFile.Length() < 1000000) // HAVE MIRRORS LEFT { mirror++; removeKeys = false; resumeIntent = false; rFile.Delete(); print("DELETE;;;"); } else { ShowDone(false); } } else { fileLength = clen + (int)total; print("FILELEN:::: " + fileLength); App.SetKey("dlength", "id" + id, fileLength); string fileExtension = MimeTypeMap.GetFileExtensionFromUrl(url); InputStream input = new BufferedInputStream(connection.InputStream); //long skip = App.GetKey<long>(DOWNLOAD_KEY, id.ToString(), 0); OutputStream output = new FileOutputStream(rFile, true); outputStreams[id] = output; inputStreams[id] = input; if (isPaused.ContainsKey(id)) { //if (isPaused[id] == 2) { // isPaused.Remove(id); return; // } } isPaused[id] = 0; activeIds.Add(id); int m3u8Progress = 0; int cProgress() { if (isM3u8) { return(m3u8Progress); } return((int)(total * 100 / fileLength)); } progress = cProgress(); byte[] data = new byte[1024]; // skip; int count; int previousProgress = 0; UpdateDloadNot(total == 0 ? "Download starting" : "Download resuming"); System.DateTime lastUpdateTime = System.DateTime.Now; long lastTotal = total; changedPause += UpdateFromId; if (isStartProgress.ContainsKey(id)) { isStartProgress.Remove(id); } bool showDone = true; bool WriteDataUpdate() { progressDownloads[id] = total; progress = cProgress(); if (isPaused[id] == 1) { print("PAUSEDOWNLOAD"); UpdateProgress(); while (isPaused[id] == 1) { Thread.Sleep(100); } if (isPaused[id] != 2) { UpdateProgress(); } } if (isPaused[id] == 2) // DELETE FILE { print("DOWNLOAD STOPPED"); ShowDone(false, "Download Stopped"); output.Flush(); output.Close(); input.Close(); outputStreams.Remove(id); inputStreams.Remove(id); isPaused.Remove(id); rFile.Delete(); App.RemoveKey(DOWNLOAD_KEY, id.ToString()); App.RemoveKey(DOWNLOAD_KEY_INTENT, id.ToString()); App.RemoveKey(App.hasDownloadedFolder, id.ToString()); App.RemoveKey("dlength", "id" + id); App.RemoveKey("DownloadIds", id.ToString()); changedPause -= UpdateFromId; activeIds.Remove(id); removeKeys = true; OnSomeDownloadFailed?.Invoke(null, EventArgs.Empty); Thread.Sleep(100); return(true); } if (DateTime.Now.Subtract(lastUpdateTime).TotalSeconds > UPDATE_TIME) { lastUpdateTime = DateTime.Now; long diff = total - lastTotal; // UpdateDloadNot($"{ConvertBytesToAny(diff/UPDATE_TIME, 2,2)}MB/s | {progress}%"); //{ConvertBytesToAny(diff / UPDATE_TIME, 2, 2)}MB/s | if (progress >= 100) { print("DLOADPG DONE!"); ShowDone(true); } else { UpdateProgress(); // UpdateDloadNot(progress + "%"); } bytesPerSec = 0; lastTotal = total; } if (progress >= 100 || progress > previousProgress) { // Only post progress event if we've made progress. previousProgress = progress; if (progress >= 100) { print("DLOADPG DONE!"); ShowDone(true); showDone = false; } else { // UpdateProgress(); // UpdateDloadNot(progress + "%"); } } return(false); } void OnError() { showDone = false; ShowDone(false, "Download Failed"); } if (isM3u8) { var links = ParseM3u8(url, referer); int counter = 0; byte[] buffer; try { while ((buffer = CloudStreamCore.DownloadByteArrayFromUrl(links[counter], referer)) != null) { counter++; m3u8Progress = counter * 100 / links.Length; count = buffer.Length; total += count; bytesPerSec += count; output.Write(buffer, 0, count); if (WriteDataUpdate()) { return; } } } catch (Exception) { OnError(); } } else { try { while ((count = input.Read(data)) != -1) { total += count; bytesPerSec += count; output.Write(data, 0, count); if (WriteDataUpdate()) { return; } } } catch (Exception) { OnError(); } } if (showDone) { ShowDone(true); } output.Flush(); output.Close(); input.Close(); outputStreams.Remove(id); inputStreams.Remove(id); activeIds.Remove(id); } } catch (Exception _ex) { print("DOWNLOADURL: " + url); print("DOWNLOAD FAILED BC: " + _ex); if (mirror < mirrors.Count - 1 && progress < 2) // HAVE MIRRORS LEFT { mirror++; removeKeys = false; resumeIntent = false; rFile.Delete(); } else { ShowDone(false); } } finally { changedPause -= UpdateFromId; isPaused.Remove(id); if (isStartProgress.ContainsKey(id)) { isStartProgress.Remove(id); } if (removeKeys) { //App.RemoveKey(DOWNLOAD_KEY, id.ToString()); //App.RemoveKey(DOWNLOAD_KEY_INTENT, id.ToString()); } else { StartT(); } } }); t.Start(); } StartT(); } catch (Exception) { } }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="NGit.Errors.CorruptObjectException"></exception> private void ReadFrom(InputStream inStream) { BufferedInputStream @in = new BufferedInputStream(inStream); MessageDigest md = Constants.NewMessageDigest(); // Read the index header and verify we understand it. // byte[] hdr = new byte[20]; IOUtil.ReadFully(@in, hdr, 0, 12); md.Update(hdr, 0, 12); if (!Is_DIRC(hdr)) { throw new CorruptObjectException(JGitText.Get().notADIRCFile); } int ver = NB.DecodeInt32(hdr, 4); bool extended = false; if (ver == 3) { extended = true; } else { if (ver != 2) { throw new CorruptObjectException(MessageFormat.Format(JGitText.Get().unknownDIRCVersion , ver)); } } entryCnt = NB.DecodeInt32(hdr, 8); if (entryCnt < 0) { throw new CorruptObjectException(JGitText.Get().DIRCHasTooManyEntries); } // Load the individual file entries. // int infoLength = DirCacheEntry.GetMaximumInfoLength(extended); byte[] infos = new byte[infoLength * entryCnt]; sortedEntries = new DirCacheEntry[entryCnt]; MutableInteger infoAt = new MutableInteger(); for (int i = 0; i < entryCnt; i++) { sortedEntries[i] = new DirCacheEntry(infos, infoAt, @in, md); } snapshot = FileSnapshot.Save(liveFile); // After the file entries are index extensions, and then a footer. // for (; ;) { @in.Mark(21); IOUtil.ReadFully(@in, hdr, 0, 20); if (@in.Read() < 0) { // No extensions present; the file ended where we expected. // break; } @in.Reset(); md.Update(hdr, 0, 8); IOUtil.SkipFully(@in, 8); long sz = NB.DecodeUInt32(hdr, 4); switch (NB.DecodeInt32(hdr, 0)) { case EXT_TREE: { if (int.MaxValue < sz) { throw new CorruptObjectException(MessageFormat.Format(JGitText.Get().DIRCExtensionIsTooLargeAt , FormatExtensionName(hdr), sz)); } byte[] raw = new byte[(int)sz]; IOUtil.ReadFully(@in, raw, 0, raw.Length); md.Update(raw, 0, raw.Length); tree = new DirCacheTree(raw, new MutableInteger(), null); break; } default: { if (hdr[0] >= 'A' && ((sbyte)hdr[0]) <= 'Z') { // The extension is optional and is here only as // a performance optimization. Since we do not // understand it, we can safely skip past it, after // we include its data in our checksum. // SkipOptionalExtension(@in, md, hdr, sz); } else { // The extension is not an optimization and is // _required_ to understand this index format. // Since we did not trap it above we must abort. // throw new CorruptObjectException(MessageFormat.Format(JGitText.Get().DIRCExtensionNotSupportedByThisVersion , FormatExtensionName(hdr))); } break; } } } byte[] exp = md.Digest(); if (!Arrays.Equals(exp, hdr)) { throw new CorruptObjectException(JGitText.Get().DIRCChecksumMismatch); } }
public static string getCharset(string fileName) { BufferedInputStream bis = null; string charset = "GBK"; byte[] first3Bytes = new byte[3]; try { bool check = false; bis = new BufferedInputStream(new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate)); bis.Mark(0); int read = bis.Read(first3Bytes, 0, 3); if (read == -1) { return(charset); } if (first3Bytes[0] == (byte)0xFF && first3Bytes[1] == (byte)0xFE) { charset = "UTF-16LE"; check = true; } else if (first3Bytes[0] == (byte)0xFE && first3Bytes[1] == (byte)0xFF) { charset = "UTF-16BE"; check = true; } else if (first3Bytes[0] == (byte)0xEF && first3Bytes[1] == (byte)0xBB && first3Bytes[2] == (byte)0xBF) { charset = "UTF-8"; check = true; } bis.Mark(0); if (!check) { while ((read = bis.Read()) != -1) { if (read >= 0xF0) { break; } if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK { break; } if (0xC0 <= read && read <= 0xDF) { read = bis.Read(); if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF) // (0x80 - 0xBF),也可能在GB编码内 { continue; } else { break; } } else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小 read = bis.Read(); if (0x80 <= read && read <= 0xBF) { read = bis.Read(); if (0x80 <= read && read <= 0xBF) { charset = "UTF-8"; break; } else { break; } } else { break; } } } } } catch (Exception e) { e.PrintStackTrace(); } finally { if (bis != null) { try { bis.Close(); } catch (IOException e) { e.PrintStackTrace(); } } } return(charset); }
public void zip() { System.IO.FileStream dest = null; ZipOutputStream out_ = null; try { dest = new System.IO.FileStream(_zipFile, System.IO.FileMode.Create); out_ = new ZipOutputStream(new System.IO.BufferedStream(dest)); byte[] data = new byte[BUFFER]; for (int i = 0; i < _files.Length; i++) { System.IO.FileStream fi = null; BufferedInputStream origin = null; try { fi = new System.IO.FileStream(_files[i], System.IO.FileMode.Open); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(Path.GetFileName(_files[i])); out_.PutNextEntry(entry); int count; //for (int b = origin.Read(); b != -1; b = origin.Read()) //{ // out_.Write(b); //} while ((count = origin.Read(data, 0, BUFFER)) != -1) { out_.Write(data, 0, count); } } finally { if (origin != null) { origin.Close(); } if (fi != null) { fi.Close(); } } } } finally { if (out_ != null) { out_.Close(); //top first } if (dest != null) { dest.Close(); } } }
//*************************************************************************************************** //******************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)); }
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; } }