0

Я разрабатывающей Android приложение, в котором мне нужно, чтобы загрузить текстовый файл, размещенный на: - https://www.dropbox.com/s/2smsdqknrjg5zda/try1.txt/?dl=0Невозможно загрузить интернет размещенный текстовый файл внутри приложения Android

внутри моего приложения и получить/загрузить его содержимое в текстовый вид. Я делаю скачивание с использованием AsyncTask's DoInBackground() метод.

Вот код в MainActivity.java, который я придумал до сих пор. Файл загружается в /storage/sdcard/file_try7.ext, но по какой-то причине его размер равен 0, который я видел в DDMS.

В разделе LogCat я получаю сообщение «java.io.FileNotFoundException».

Может кто-то пожалуйста взглянуть и посмотреть, что может быть проблема .. ??

package com.example.xxxxx;

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 

import android.support.v7.app.ActionBarActivity; 
import android.support.v7.app.ActionBar; 
import android.support.v4.app.Fragment; 
import android.text.InputFilter.LengthFilter; 
import android.database.Cursor; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.Environment; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.EditText; 
import android.widget.Toast; 
import android.os.Build; 
import android.provider.MediaStore; 

public class MainActivity extends ActionBarActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 



     if (savedInstanceState == null) { 
      getSupportFragmentManager().beginTransaction() 
        .add(R.id.container, new PlaceholderFragment()).commit(); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 

     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    /** 
    * A placeholder fragment containing a simple view. 
    */ 
    public static class PlaceholderFragment extends Fragment { 

     public PlaceholderFragment() { 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_main, container, 
        false); 
      return rootView; 
     } 
    } 

    private class MyAsyncTask extends AsyncTask<Void, Void, Void>{ 

     //execute on background (out of the UI thread) 




    @Override 
    protected Void doInBackground(Void... params) { 
     try { 
      //set the download URL, a url that points to a file on the internet 
      //this is the file to be downloaded 


      URL url = new URL("https://www.dropbox.com/s/2smsdqknrjg5zda/try1.txt/?dl=0"); 

      //create the new connection 
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

      //set up some things on the connection 
      urlConnection.setRequestMethod("GET"); 
      urlConnection.setDoOutput(true); 

      //and connect! 
      urlConnection.connect(); 

      //set the path where we want to save the file 
      //in this case, going to save it on the root directory of the 
      //sd card. 
      File SDCardRoot = Environment.getExternalStorageDirectory(); 
      //create a new file, specifying the path, and the filename 
      //which we want to save the file as. 
      File file = new File(SDCardRoot,"menu7.ext"); 
    //  if (!file.exists()) { 
     //   file.createNewFile(); 
     // } 

      //this will be used to write the downloaded data into the file we created 
      FileOutputStream fileOutput = new FileOutputStream(file); 

      //this will be used in reading the data from the internet 
      InputStream inputStream = urlConnection.getInputStream(); 

      //this is the total size of the file 
      int totalSize = urlConnection.getContentLength(); 
      //variable to store total downloaded bytes 
      int downloadedSize = 0; 

      //create a buffer... 
      byte[] buffer = new byte[1024]; 
      int bufferLength = 0; //used to store a temporary size of the buffer 

      //now, read through the input buffer and write the contents to the file 
      while ((bufferLength = inputStream.read(buffer)) > 0) { 
        //add the data in the buffer to the file in the file output stream (the file on the sd card 
        fileOutput.write(buffer, 0, bufferLength); 
        //add up the size so we know how much is downloaded 
        downloadedSize += bufferLength; 
        //this is where you would do something to report the prgress, like this maybe 
        //updateProgress(downloadedSize, totalSize); 

      } 
      //close the output stream when done 
      fileOutput.close(); 

    //catch some possible errors... 
    } catch (MalformedURLException e) { 
      e.printStackTrace(); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
     // TODO Auto-generated method stub 
     return null; 
    } 


} 
    public void get_menu(View v) 
    { 
     MyAsyncTask async = new MyAsyncTask(); 
     async.execute(); 
     //Toast.makeText(this.getApplicationContext(),"Inside get_menu",Toast.LENGTH_SHORT).show(); 
      } 

    //Method to get the FileInputStream object as a string. 
      public static String convertStreamToString(InputStream is) throws Exception { 
       BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 
       while ((line = reader.readLine()) != null) { 
        sb.append(line).append("\n"); 
       } 
       reader.close(); 
       return sb.toString(); 
      } 

      /*Method to get text of the file with path as filePath as string by calling 
       convertStreamToString.*/ 
      public static String getStringFromFile (String filePath) throws Exception { 
       File fl = new File(filePath); 
       FileInputStream fin = new FileInputStream(fl); 
       String ret = convertStreamToString(fin); 
       fin.close();   
       return ret; 
      } 



    public void load_menu(View v) 
    { 
     //Method which actually loads the text by calling the getStringFromFile method. 
      String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath(); 
      EditText editText2=(EditText)findViewById(R.id.editText2); 
      //String fileName=editText2.getText().toString(); 
      String path = baseDir + "/" + "menu7" + ".ext"; 

      try { 
        String inp_string=getStringFromFile(path); 
       //EditText editText1=(EditText)findViewById(R.id.editText1); 
       editText2.setText(inp_string); 
      } catch (Exception e) { 
       Toast.makeText(this.getApplicationContext(),"File not found.",Toast.LENGTH_SHORT).show(); 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 





    } 

} 

ответ

0

Вы открываете URL с помощью метода GET, и именно поэтому он не дает вам выходной файл в буфер, но ссылку, чтобы загрузить файл. проверьте снимок экрана ниже. Убедитесь, что вы загрузили файл, а затем загрузите файл в буфер. Но мне интересно, зачем вам это нужно, если вы уже загрузили файл.

http://i.stack.imgur.com/w6AnN.png

+0

Не могли бы вы сказать мне, как скачать файл, а не ссылку .. ?? Кроме того, файл еще не был загружен, он загружается из приложения, когда пользователь нажимает кнопку. –

+0

вам нужно использовать класс менеджера загрузки для документации по android. Это простой процесс. Это хорошо объяснено на их веб-сайте. Если вам нужна помощь после публикации здесь. – Prashant18

Смежные вопросы