Java review day 1-basic knowledge of Javascript

Source: Internet
Author: User

 
 
Packagecom. example. download; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. inputStream; import java. io. randomAccessFile; import java.net. httpURLConnection; import java.net. URL; import android. app. activity; import android. OS. bundle; import android. OS. environment; import android. OS. handler; import android. text. textUtils; import android. view. view; import Ndroid. widget. editText; import android. widget. progressBar; import android. widget. textView; import android. widget. toast; public class MainActivity extends Activity {// defines the number of running threads private int threadRunning = 3; // Number of threads enabled private int threadNum = 3; private EditText et_url; // progress bar private ProgressBar progressBar; private TextView TV _pb; private int currentProgress = 0; private boolean flag = true; // record the progress bar value public Static int pb_count = 0; public static Handler handler; public static final int TEXTVALUE = 1; public static int pb_num = 0; public static int size = 0; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the control object et_url = (EditText) findViewById (R. id. et_url); progressBar = (ProgressBar) findViewById (R. id. TV _jindu); TV _pb = (TextView) findViewById (R. id. TV _pb); File sdDir = Environment. getExternalStorageDirectory (); File pdFile = new File (sdDir, pb.txt); InputStream is = null; try {if (pdFile. exists () {is = new FileInputStream (pdFile) ;}} catch (FileNotFoundException e) {e. printStackTrace ();} if (is! = Null) {String value = StreamTools. streamTostr (is); String arr [] = value. split (;); progressBar. setMax (Integer. valueOf (arr [0]); // maximum value currentProgress = Integer. valueOf (arr [1]); // current value progressBar. setProgress (currentProgress); TV _pb.setText (the current progress is + arr [2] + %) ;}} public void downLoadFile (View v) {// access address: final String spec = et_url.getText (). toString (); // http: // 172.16.237.144: 8080/Login/football.jpg; if (TextUtils. isEmpty (spec) {Toast. makeText (this, cannot be empty, Toast. LENGTH_LONG ). show () ;}else {new Thread () {public void run () {try {URL url URL = new url (spec); HttpURLConnection httpURLConnection = (HttpURLConnection) URL. openConnection (); // you can specify whether the header file of the request has a time of httpURLConnection. setRequestMethod (GET); httpURLConnection. setConnectTimeout (5000); httpURLConnection. setReadTimeout (5000); if (httpURLConnection. getResponse Code () == 200) {int fileLength = httpURLConnection. getContentLength (); // set the maximum value of the progress bar. setMax (fileLength); // determines whether your device SDCard is available if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {// path of the External Storage Device File sdfile = Environment. getExternalStorageDirectory (); // get the file name String fileName = spec. substring (spec. lastIndexOf (/) + 1); // create the saved File file File = new File (sdfile, fileName); // create File object RandomAccessFile accessFile = new RandomAccessFile (file, rwd); // set the file size accessFile. setLength (fileLength); // close the accessFile operation. close (); // calculate the download size of each thread, start position, end position, int threadSize = fileLength/threadNum; // for Loop, enable thread processing for (int threadId = 1; threadId <= 3; threadId ++) {int startIndex = (threadId-1) * threadSize; // start position int endIndex = threadId * threadSize-1; if (threadId = threadNum) {// The Last Thread endIndex = fileLength-1;} System. out. println (current thread -- + threadId + Start position --- + startIndex + end position --- + endIndex + thread size ---); // to Start thread download, use the Start method new DownLoadThread (threadId, startIndex, endIndex, spec, fileName ). start () ;}} else {MainActivity. this. runOnUiThread (new Runnable () {@ Overridepublic void run () {Toast. makeText (MainActivity. this, the device's SD card is not available, Toast. LENGTH_LONG ). show () ;}} else {// use this to run Ma in the main thread InActivity. this. runOnUiThread (new Runnable () {@ Overridepublic void run () {Toast. makeText (MainActivity. this, the server returns an error, Toast. LENGTH_LONG ). show () ;}) ;}} catch (Exception e) {e. printStackTrace ();}};}. start () ;}} class DownLoadThread extends Thread {private int threadId; private int startIndex; private int endIndex; private String path; private String fileName; public DownLoadThread (int threadId, int startInd Ex, int endIndex, String path, String fileName) {super (); this. threadId = threadId; this. startIndex = startIndex; this. endIndex = endIndex; this. path = path; this. fileName = fileName;} @ Overridepublic void run () {// you can download files through each thread. Try {File sdfile = Environment. getExternalStorageDirectory (); // obtain the record File downloaded by each thread. File recordFile = new File (sdfile, threadId +. txt); // determine whether the record file exists if (recordFile. exists () {// read the file content InputStream is = new FileInputStream (recordFile); // use the tool class to convert String value = StreamTools. streamTostr (is); // obtain the record position int recordIndex = Integer. parseInt (value); // copy the record location to the start location. startIndex = recordIndex;} // construct the URL object URL through the path = New URL (path); // use the URL object to open the connection and return the HttpURLConnection httpURLConnection = (HttpURLConnection) url. openConnection (); // sets the request header httpURLConnection. setRequestMethod (GET); httpURLConnection. setConnectTimeout (5000); // sets the start position and end position of the downloaded object. httpURLConnection. setRequestProperty (Range, bytes = + startIndex +-+ endIndex); // obtain the status int code = httpURLConnection. getResponseCode (); if (code = 206) {// gets the stream object returned by each thread: InputSt Ream inputStream = httpURLConnection. getInputStream (); // get the file name because it has been passed over. // String fileName = // path. substring (path. lastIndexOf (/) + 1); // path of the external storage device File = new file (sdfile, fileName ); // create her RandomAccessFile object RandomAccessFile raf = new RandomAccessFile (file, rwd); raf. seek (startIndex); // defines the read length int len = 0; byte buffer [] = new byte [50]; int total = 0; // read the while (len = inputStream. read (buffe R ))! =-1) {System. out. println (current thread -- + threadId + -- Downloaded + (startIndex + total); // create the File RandomAccessFile threadfile = new RandomAccessFile (new File (sdfile, threadId +. txt), rwd); threadfile. writeBytes (startIndex + total) +); threadfile. close (); raf. write (buffer, 0, len); total + = len; synchronized (MainActivity. this) {currentProgress + = len; progressBar. setProgress (currentProgress); // calculate the percentage of intfinal String percent = currentProgress * 100L/progressBar. getMax () +; MainActivity. this. runOnUiThread (new Runnable () {@ Overridepublic void run () {TV _pb.setText (the current progress is + percent + % );}}); randomAccessFile pbfile = new RandomAccessFile (new File (sdfile, pb.txt), rwd); pbfile. writeBytes (progressBar. getMax () ++ currentProgress ++; + percent); pbfile. close () ;}} raf. close (); inputStream. close (); MainActivity. this. runOnUiThread (new Runnable () {@ Overridepublic void run () {// System. out. println (current thread ---- + threadId + download completed); Toast. makeText (MainActivity. this, the current thread ---- + threadId + download is complete, Toast. LENGTH_LONG ). show () ;}}); deleteRecordFiles () ;}else {MainActivity. this. runOnUiThread (new Runnable () {@ Overridepublic void run () {Toast. makeText (MainActivity. this indicates a Server Download error. LENGTH_LONG ). show () ;}) ;}} catch (Exception e) {e. printStackTrace () ;}} public synchronized void deleteRecordFiles () {File sdfile = Environment. getExternalStorageDirectory (); System. out. println (-------------------------); threadRunning --; if (threadRunning = 0) {for (int I = 1; I <= 3; I ++) {File recordFile = new File (sdfile, I +. txt); if (recordFile. exists () {boolean flag1 = recordFile. delete (); // delete the file System. out. println (download record + I + File already + flag1 + deleted);} File pdFile = new File (sdfile, pb.txt); if (pdFile. exists () {boolean flag2 = pdFile. delete (); System. out. println (progress bar recording file + flag2 + deleted); }}} public void displayMsg (){}}


BUG considerations:

1. threadfile. close () must be executed to continue the download of files from the thread. Otherwise, the TXT file cannot be deleted.

2. Be sure to pay attention to the download speed setting. The download speed cannot be too fast and the size of the file to be transferred exceeds. Otherwise, the simulator will die .;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.