Author Topic: How to read a text file from a website?  (Read 4629 times)

Offline Melssj5

  • double
  • *****
  • Posts: 724
    • View Profile
How to read a text file from a website?
« on: October 01, 2008, 03:17:39 am »
Hi all, I need to read a text file from a website, for example:

http://localhost:2020/project/file.txt

I must read that file from my desktop application. Any ideas? This is really urgent and I dont have any ideas, I never have done that but was trying to do it with Streams, Files, URI, URL, etc etc. But I am just gessing and coding. Please any help would be very appreciated.
Nada por ahora

Offline paulscode

  • double
  • *****
  • Posts: 863
    • View Profile
    • PaulsCode.Com
Re: How to read a text file from a website?
« Reply #1 on: October 01, 2008, 03:32:16 am »
Something like this should work (not tested)

Code: [Select]
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

// ...

public void readASCIIFileFromURL()
{
    try
    {
        URL url = new URL( "http://localhost:2020/project/file.txt" );
        InputStream in = url.openStream();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ByteArrayInputStream bin = null;
        BufferedReader bufRead = null;

        byte buffer[] = new byte[4096];
        int read = 0;
        do
        {
            read = in.read( buffer );
            if( read != -1 )
                bout.write( buffer, 0, read );
        } while( read != -1 );
       
        //copy binary to an input stream for reading and parsing
        bin = new ByteArrayInputStream( bout.toByteArray() );
        bufRead = new BufferedReader( new InputStreamReader( bin ) );
       
        String line = "";
        do
        {
            line = bufRead.readLine();
            if( line != null )
            {
                // Do something with the line of text here.
                System.out.println( line );
            }
        } while( line != null );
        in.close();
        bout.close();
        bin.close();
        bufRead.close();
    }
    catch( Exception e )
    {
        e.printStackTrace();
    }
}