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.
Something like this should work (not tested)
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();
}
}