Search code examples
javaandroiddownloadinputstreamtxtextcontrol

Android download txt from website without removing wrap


I need to download a .txt file from a website, the problem is the downloaded file doesn't respect the same line wrapping as the original file. File:

Word1
Word2
Word3 

File downloaded:

Word1Word2Word3

I use this method to download (this isn't mine) :

@Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            int lenghtOfFile = conection.getContentLength();

            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            OutputStream output = new FileOutputStream( MegaMethods.FolderPath+"downloadedfile.txt");

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress(""+(int)((total*100)/lenghtOfFile));
                output.write(data, 0, count);
            }
            output.flush();

            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return null;
    }

Solution

  • Try using a BufferedReader to read it in something like

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = null;
    
    StringBuilder responseData = new StringBuilder();
    while((line = in.readLine()) != null) {
        responseData.append(line);
    }
    

    then output the lines as necessary. I'm no where near a station where I can test this so you might have to do some fiddling.