无法从Android应用程序内下载internet托管的文本文件
我正在开发一个Android应用程序,其中我需要下载一个托管在以下位置的文本文件:- 从我的应用程序中,在文本视图中获取/加载其内容。 我正在使用AsyncTask的doInBackground()方法进行下载 下面是我到目前为止所得到的MainActivity.java中的代码。 该文件将在/storage/sdcard/file_try7.ext中下载,但由于某些原因,它的大小为0,这是我在DDMS中看到的 在LogCat部分,我收到消息“java.io.FileNotFoundException” 有人能看一看,看看可能是什么问题吗 包com.example.xxxxx无法从Android应用程序内下载internet托管的文本文件,android,url,android-asynctask,network-protocols,filenotfoundexception,Android,Url,Android Asynctask,Network Protocols,Filenotfoundexception,我正在开发一个Android应用程序,其中我需要下载一个托管在以下位置的文本文件:- 从我的应用程序中,在文本视图中获取/加载其内容。 我正在使用AsyncTask的doInBackground()方法进行下载 下面是我到目前为止所得到的MainActivity.java中的代码。 该文件将在/storage/sdcard/file_try7.ext中下载,但由于某些原因,它的大小为0,这是我在DDMS中看到的 在LogCat部分,我收到消息“java.io.FileNotFoundExcep
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();
}
}
}
导入java.io.BufferedReader;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.net.HttpURLConnection;
导入java.net.MalformedURLException;
导入java.net.URL;
导入android.support.v7.app.ActionBarActivity;
导入android.support.v7.app.ActionBar;
导入android.support.v4.app.Fragment;
导入android.text.InputFilter.LengthFilter;
导入android.database.Cursor;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.os.Environment;
导入android.view.LayoutInflater;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.EditText;
导入android.widget.Toast;
导入android.os.Build;
导入android.provider.MediaStore;
公共类MainActivity扩展了ActionBarActivity{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
如果(savedInstanceState==null){
getSupportFragmentManager().beginTransaction()
.add(R.id.container,新的占位符片段()).commit();
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
if(id==R.id.action\u设置){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
/**
*包含简单视图的占位符片段。
*/
公共静态类占位符片段扩展了片段{
公共占位符片段(){
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图根视图=充气机。充气(R.layout.fragment_main,容器,
假);
返回rootView;
}
}
私有类MyAsyncTask扩展了AsyncTask{
//在后台执行(在UI线程之外)
@凌驾
受保护的Void doInBackground(Void…参数){
试一试{
//设置下载URL,该URL指向internet上的文件
//这是要下载的文件
URL=新URL(“https://www.dropbox.com/s/2smsdqknrjg5zda/try1.txt/?dl=0");
//创建新连接
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
//在连接上设置一些东西
urlConnection.setRequestMethod(“GET”);
urlConnection.setDoOutput(true);
//连接!
urlConnection.connect();
//设置要保存文件的路径
//在本例中,将其保存在
//sd卡。
文件SDCardRoot=Environment.getExternalStorageDirectory();
//创建一个新文件,指定路径和文件名
//我们希望将文件另存为。
File File=新文件(SDCardRoot,“menu7.ext”);
//如果(!file.exists()){
//createNewFile();
// }
//这将用于将下载的数据写入我们创建的文件中
FileOutputStream fileOutput=新的FileOutputStream(文件);
//这将用于从互联网读取数据
InputStream InputStream=urlConnection.getInputStream();
//这是文件的总大小
int totalSize=urlConnection.getContentLength();
//用于存储总下载字节数的变量
int downloadedSize=0;
//创建一个缓冲区。。。
字节[]缓冲区=新字节[1024];
int bufferLength=0;//用于存储缓冲区的临时大小
//现在,读取输入缓冲区并将内容写入文件
而((bufferLength=inputStream.read(buffer))>0){
//将缓冲区中的数据添加到文件输出流中的文件(sd卡上的文件)
fileOutput.write(buffer,0,bufferLength);
//把大小加起来,这样我们就知道下载了多少
downloadedSize+=缓冲区长度;
//在这里,你可以做一些事情来报告事件,也许像这样
//updateProgress(downloadedSize,totalSize);
}
//完成后关闭输出流
fileOutput.close();
//捕捉一些可能的错误。。。
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
//托多汽车公司