从URL读取txt并追加字符串

时间:2016-08-26 17:22:42

标签: android string url

我有以下代码从url读取txt文件并附加到代码中的新url。但我的代码不起作用。我该如何更正代码?此外,当我从URL URL url = new URL("https://example.com/thefile.txt");读取txt时,应用程序停止。需要帮助。我是android新手,我可以获得编辑过的解决方案。提前谢谢。

import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import com.package.name.common.ActivityBase;



public class MyActivity extends ActivityBase {

    Toolbar mToolbar;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_activity);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);


        try {
            // Create a URL for the desired page
            URL url = new URL("example.com/thefile.txt");

            // Read all the text returned by the server
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuilder builder = new StringBuilder();
            String str;
            while ((str = in.readLine()) != null) {
                // str is one line of text; readLine() strips the newline character(s)
                builder.append(str);
            }
            in.close();
            String yourData = builder.toString();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }

               // Loader image - will be shown before loading image
        int loader = R.drawable.loader;
        ImageView image = (ImageView) findViewById(R.id.image);

        String image_url = "http://example.com/data/" + yourData;

        ImageLoader imgLoader = new ImageLoader(getApplicationContext());

        imgLoader.DisplayImage(image_url, loader, image);
    }
    @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.\

        switch (item.getItemId()) {

            case android.R.id.home: {

                finish();
                return true;
            }

            default: {

                return super.onOptionsItemSelected(item);
            }
        }
    }
}

0 个答案:

没有答案
相关问题